Platform version check during wgt installation - fixed
[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 <sstream>
24 #include <string>
25 #include <sys/stat.h>
26 #include <dirent.h>
27
28 #include <dpl/errno_string.h>
29 #include <dpl/foreach.h>
30 #include <dpl/localization/w3c_file_localization.h>
31 #include <dpl/singleton_impl.h>
32 #include <dpl/utils/mime_type_utils.h>
33 #include <dpl/utils/wrt_global_settings.h>
34 #include <dpl/utils/wrt_utility.h>
35 #include <dpl/wrt-dao-ro/global_config.h>
36 #include <dpl/wrt-dao-rw/feature_dao.h>
37
38 #include <libiriwrapper.h>
39 #include <parser_runner.h>
40 #include <root_parser.h>
41
42 #include <widget_install/job_widget_install.h>
43 #include <widget_install/task_widget_config.h>
44 #include <widget_install/widget_install_context.h>
45 #include <widget_install/widget_install_errors.h>
46 #include <widget_parser.h>
47 #include <wrt_error.h>
48
49
50 namespace { // anonymous
51 const DPL::String BR = DPL::FromUTF8String("<br>");
52 const std::string WIDGET_NOT_COMPATIBLE = "This widget is "
53         "not compatible with WRT.<br><br>";
54 const std::string QUESTION = "Do you want to install it anyway?";
55
56 const char *const DEFAULT_LANGUAGE = "default";
57
58 const char *const WRT_WIDGET_CONFIG_FILE_NAME = "config.xml";
59
60 const std::string WINDGET_INSTALL_NETWORK_ACCESS = "network access";
61 }
62
63
64 namespace Jobs {
65 namespace WidgetInstall {
66 void InstallerTaskWidgetPopupData::PopupData::addWidgetInfo(
67         const DPL::String &info)
68 {
69     widgetInfo = info;
70 }
71
72 TaskWidgetConfig::TaskWidgetConfig(InstallerContext& installContext) :
73     DPL::TaskDecl<TaskWidgetConfig>(this),
74     WidgetInstallPopup(installContext),
75     m_installContext(installContext)
76
77 {
78     AddStep(&TaskWidgetConfig::StepProcessConfigurationFile);
79     AddStep(&TaskWidgetConfig::ReadLocaleFolders);
80     AddStep(&TaskWidgetConfig::ProcessLocalizedStartFiles);
81     AddStep(&TaskWidgetConfig::ProcessBackgroundPageFile);
82     AddStep(&TaskWidgetConfig::ProcessLocalizedIcons);
83     AddStep(&TaskWidgetConfig::StepVerifyFeatures);
84     AddStep(&TaskWidgetConfig::StepCheckMinVersionInfo);
85
86     if (!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet) {
87         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures);
88         AddStep(&TaskWidgetConfig::StepShowWidgetInfo);
89         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallation);
90         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion);
91         AddStep(&TaskWidgetConfig::StepDeletePopupWin);
92     }
93 }
94
95 void TaskWidgetConfig::StepProcessConfigurationFile()
96 {
97     Try
98     {
99         std::string path = m_installContext.locations->getConfigurationDir();
100         LogInfo("path: " << path);
101
102         processFile(path, m_installContext.widgetConfig);
103     }
104     Catch(Exception::ConfigParseFailed)
105     {
106         LogError("Parsing failed.");
107         ReThrow(Exceptions::WidgetConfigFileInvalid);
108     }
109     Try
110     {
111         // To get widget type for distribute WAC, TIZEN WebApp
112         setApplicationType();
113     }
114     Catch(Exception::ConfigParseFailed)
115     {
116         LogError("Config.xml has more than one namespace");
117         ReThrow(Exceptions::WidgetConfigFileInvalid);
118     }
119
120     m_installContext.job->UpdateProgress(
121         InstallerContext::INSTALL_WIDGET_CONFIG1,
122         "Parse elements of configuration file and save them");
123 }
124
125 void TaskWidgetConfig::ReadLocaleFolders()
126 {
127     LogDebug("Reading locale");
128     //Adding default locale
129     m_localeFolders.insert(L"");
130
131     std::string localePath = m_installContext.locations->getConfigurationDir() + "/locales";
132     DIR* localeDir = opendir(localePath.c_str());
133     if (!localeDir) {
134         LogDebug("No /locales directory in the widget package.");
135         return;
136     }
137
138     struct dirent* dirent;
139     struct stat statStruct;
140     do {
141         errno = 0;
142         if ((dirent = readdir(localeDir))) {
143             DPL::String dirName = DPL::FromUTF8String(dirent->d_name);
144             std::string absoluteDirName = localePath + "/";
145             absoluteDirName += dirent->d_name;
146
147             if (stat(absoluteDirName.c_str(), &statStruct) != 0) {
148                 LogError("stat() failed with " << DPL::GetErrnoString());
149                 continue;
150             }
151
152             if (S_ISDIR(statStruct.st_mode)) {
153                 //Yes, we ignore current, parent & hidden directories
154                 if (dirName[0] != L'.') {
155                     LogDebug("Adding locale directory \"" << dirName << "\"");
156                     m_localeFolders.insert(dirName);
157                 }
158             }
159         }
160     }
161     while (dirent);
162
163     if (errno != 0) {
164         LogError("readdir() failed with " << DPL::GetErrnoString());
165     }
166
167     if (-1 == TEMP_FAILURE_RETRY(closedir(localeDir))) {
168         LogError("Failed to close dir: " << localePath << " with error: "
169                 << DPL::GetErrnoString());
170     }
171 }
172
173 void TaskWidgetConfig::ProcessLocalizedStartFiles()
174 {
175     typedef DPL::String S;
176     ProcessStartFile(
177         m_installContext.widgetConfig.configInfo.startFile,
178         m_installContext.widgetConfig.configInfo.
179             startFileContentType,
180         m_installContext.widgetConfig.configInfo.startFileEncoding,
181         true);
182     ProcessStartFile(S(L"index.htm"), S(L"text/html"));
183     ProcessStartFile(S(L"index.html"), S(L"text/html"));
184     ProcessStartFile(S(L"index.svg"), S(L"image/svg+xml"));
185     ProcessStartFile(S(L"index.xhtml"), S(L"application/xhtml+xml"));
186     ProcessStartFile(S(L"index.xht"), S(L"application/xhtml+xml"));
187     // TODO: (l.wrzosek) we need better check if in current locales widget is valid.
188     FOREACH(it, m_installContext.widgetConfig.localizationData.startFiles) {
189         if (it->propertiesForLocales.size() > 0) {
190             return;
191         }
192     }
193     ThrowMsg(Exceptions::WidgetConfigFileInvalid,
194              L"The Widget has no valid start file");
195 }
196
197 void TaskWidgetConfig::ProcessStartFile(const DPL::OptionalString& path,
198         const DPL::OptionalString& type,
199         const DPL::OptionalString& encoding,
200         bool typeForcedInConfig)
201 {
202     using namespace WrtDB;
203
204     if (!!path) {
205         WidgetRegisterInfo::LocalizedStartFile startFileData;
206         startFileData.path = *path;
207
208         FOREACH(i, m_localeFolders) {
209             DPL::String pathPrefix = *i;
210             if (!pathPrefix.empty()) {
211                 pathPrefix = L"locales/" + pathPrefix + L"/";
212             }
213
214             DPL::String relativePath = pathPrefix + *path;
215             DPL::String absolutePath = DPL::FromUTF8String(
216                     m_installContext.locations->getConfigurationDir()) + L"/" + relativePath;
217
218             // get property data from packaged app
219             if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
220                 WidgetRegisterInfo::StartFileProperties startFileProperties;
221                 if (!!type) {
222                     startFileProperties.type = *type;
223                 } else {
224                     startFileProperties.type =
225                         MimeTypeUtils::identifyFileMimeType(absolutePath);
226                 }
227
228                 //proceed only if MIME type is supported
229                 if (MimeTypeUtils::isMimeTypeSupportedForStartFile(
230                         startFileProperties.type))
231                 {
232                     if (!!encoding) {
233                         startFileProperties.encoding = *encoding;
234                     } else {
235                         MimeTypeUtils::MimeAttributes attributes =
236                             MimeTypeUtils::getMimeAttributes(
237                             startFileProperties.type);
238                         if (attributes.count(L"charset") > 0) {
239                             startFileProperties.encoding =
240                                 attributes[L"charset"];
241                         } else {
242                             startFileProperties.encoding = L"UTF-8";
243                         }
244                     }
245
246                     startFileData.propertiesForLocales[*i] =
247                         startFileProperties;
248                 } else {
249                     //9.1.16.5.content.8
250                     //(there seems to be no similar requirement in .6,
251                     //so let's throw only when mime type is
252                     // provided explcitly in config.xml)
253                     if (typeForcedInConfig) {
254                         ThrowMsg(Exceptions::WidgetConfigFileInvalid,
255                                  "Unsupported MIME type for start file.");
256                     }
257                 }
258             } else {
259                 // set property data for hosted start url
260                 // Hosted start url only support TIZEN WebApp
261                 if (m_installContext.widgetConfig.webAppType ==
262                         APP_TYPE_TIZENWEBAPP)
263                 {
264                     const char *startPath =
265                         DPL::ToUTF8String(startFileData.path).c_str();
266                     if (strstr(startPath, "http") == startPath) {
267                         WidgetRegisterInfo::StartFileProperties
268                             startFileProperties;
269                         if (!!type) {
270                             startFileProperties.type = *type;
271                         }
272                         if (!!encoding) {
273                             startFileProperties.encoding = *encoding;
274                         }
275                         startFileData.propertiesForLocales[*i] =
276                             startFileProperties;
277                     }
278                 }
279             }
280         }
281
282         m_installContext.widgetConfig.localizationData.startFiles.push_back(
283             startFileData);
284     }
285 }
286
287 void TaskWidgetConfig::ProcessBackgroundPageFile()
288 {
289     if (!!m_installContext.widgetConfig.configInfo.backgroundPage) {
290         // check whether file exists
291         DPL::String backgroundPagePath = DPL::FromUTF8String(
292             m_installContext.locations->getConfigurationDir()) + L"/" +
293             *m_installContext.widgetConfig.configInfo.backgroundPage;
294         //if no then cancel installation
295         if (!WrtUtilFileExists(DPL::ToUTF8String(backgroundPagePath))) {
296             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
297                     L"Given background page file not found in archive");
298         }
299     }
300 }
301
302 void TaskWidgetConfig::ProcessLocalizedIcons()
303 {
304     using namespace WrtDB;
305     ProcessIcon(ConfigParserData::Icon(L"icon.svg"));
306     ProcessIcon(ConfigParserData::Icon(L"icon.ico"));
307     ProcessIcon(ConfigParserData::Icon(L"icon.png"));
308     ProcessIcon(ConfigParserData::Icon(L"icon.gif"));
309     ProcessIcon(ConfigParserData::Icon(L"icon.jpg"));
310
311     FOREACH(i, m_installContext.widgetConfig.configInfo.iconsList)
312     {
313         ProcessIcon(*i);
314     }
315 }
316
317 void TaskWidgetConfig::ProcessIcon(const WrtDB::ConfigParserData::Icon& icon)
318 {
319     LogInfo("enter");
320     bool isAnyIconValid = false;
321     //In case a default filename is passed as custom filename in config.xml, we
322     //need to keep a set of already processed filenames to avoid icon duplication
323     //in database.
324
325     using namespace WrtDB;
326
327     if (m_processedIconSet.count(icon.src) > 0) {
328         return;
329     }
330     m_processedIconSet.insert(icon.src);
331
332     LocaleSet localesAvailableForIcon;
333
334     FOREACH(i, m_localeFolders)
335     {
336         DPL::String pathPrefix = *i;
337         if (!pathPrefix.empty()) {
338             pathPrefix = L"locales/" + pathPrefix + L"/";
339         }
340
341         DPL::String relativePath = pathPrefix + icon.src;
342         DPL::String absolutePath = DPL::FromUTF8String(
343                 m_installContext.locations->getConfigurationDir()) + L"/" + relativePath;
344
345         if (WrtUtilFileExists(DPL::ToUTF8String(absolutePath))) {
346             DPL::String type = MimeTypeUtils::identifyFileMimeType(absolutePath);
347
348             if (MimeTypeUtils::isMimeTypeSupportedForIcon(type)) {
349                 isAnyIconValid = true;
350                 localesAvailableForIcon.insert(*i);
351                 LogInfo("Icon absolutePath :" << absolutePath <<
352                         ", assigned locale :" << *i << ", type: " << type);
353             }
354         }
355     }
356
357     if(isAnyIconValid)
358     {
359         WidgetRegisterInfo::LocalizedIcon localizedIcon(icon,
360                                                         localesAvailableForIcon);
361         m_installContext.widgetConfig.localizationData.icons.push_back(
362             localizedIcon);
363     }
364 }
365
366 void TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures()
367 {
368     LogDebug("StepCancelWidgetInstallationAfterVerifyFeatures");
369     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
370         m_installCancel = WRT_POPUP_BUTTON;
371         destroyPopup();
372         ThrowMsg(Exceptions::WidgetConfigFileInvalid, "Widget not allowed");
373     }
374 }
375
376 void TaskWidgetConfig::StepCancelWidgetInstallation()
377 {
378     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
379         m_installCancel = WRT_POPUP_BUTTON;
380         destroyPopup();
381         ThrowMsg(Exceptions::NotAllowed, "Widget not allowed");
382     }
383 }
384
385 void TaskWidgetConfig::StepCancelWidgetInstallationAfterMinVersion()
386 {
387     if (InfoPopupButton::WRT_POPUP_BUTTON_CANCEL == m_installCancel) {
388         m_installCancel = WRT_POPUP_BUTTON;
389         destroyPopup();
390         ThrowMsg(Exceptions::NotAllowed, "WRT version incompatible.");
391     }
392 }
393
394 void TaskWidgetConfig::createInstallPopup(PopupType type, const std::string &label)
395 {
396     m_installContext.job->Pause();
397     if (m_popup)
398         destroyPopup();
399
400     bool ret = createPopup();
401     if (ret)
402     {
403         loadPopup( type, label);
404         showPopup();
405     }
406 }
407
408 void TaskWidgetConfig::StepDeletePopupWin()
409 {
410     destroyPopup();
411 }
412
413 void TaskWidgetConfig::StepShowWidgetInfo()
414 {
415     if (!m_popupData.widgetInfo.empty()) {
416             std::string label = DPL::ToUTF8String(m_popupData.widgetInfo);
417             createInstallPopup(PopupType::WIDGET_FEATURE_INFO, label);
418         m_installContext.job->UpdateProgress(
419             InstallerContext::INSTALL_WIDGET_CONFIG2,
420             "Show Widget Info Finished");
421     }
422 }
423
424 void TaskWidgetConfig::StepCheckMinVersionInfo()
425 {
426     if (!isMinVersionCompatible(
427                 m_installContext.widgetConfig.webAppType.appType,
428                 m_installContext.widgetConfig.minVersion)) {
429         if(!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet)
430         {
431             LogDebug("Platform version to low - launching");
432             std::string label = WIDGET_NOT_COMPATIBLE + QUESTION;
433             createInstallPopup(PopupType::WIDGET_MIN_VERSION, label);
434         }
435         else
436         {
437             LogError("Platform version lower than required -> cancelling installation");
438             ThrowMsg(Exceptions::NotAllowed,
439                     "Platform version does not meet requirements");
440         }
441     }
442
443     m_installContext.job->UpdateProgress(
444             InstallerContext::INSTALL_WIDGET_CONFIG2,
445             "Check MinVersion Finished");
446 }
447
448 void TaskWidgetConfig::StepVerifyFeatures()
449 {
450     using namespace WrtDB;
451     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
452     ConfigParserData::FeaturesList list = data.featuresList;
453     ConfigParserData::FeaturesList newList;
454
455     //in case of tests, this variable is unused
456     std::string featureInfo;
457     FOREACH(it, list)
458     {
459         // check feature vender for permission
460         // WAC, TIZEN WebApp cannot use other feature
461
462         if (!isFeatureAllowed(m_installContext.widgetConfig.webAppType.appType,
463                               it->name))
464         {
465             LogInfo("This application type not allowed to use this feature");
466             ThrowMsg(
467                 Exceptions::WidgetConfigFileInvalid,
468                 "This app type [" <<
469                 m_installContext.widgetConfig.webAppType.getApptypeToString() <<
470                 "] cannot be allowed to use [" <<
471                 DPL::ToUTF8String(it->name) + "] feature");
472         }
473         if (!WrtDB::FeatureDAOReadOnly::isFeatureInstalled(
474                 DPL::ToUTF8String(it->name))) {
475             LogWarning("Feature not found. Checking if required :[" <<
476                        DPL::ToUTF8String(it->name) << "]");
477
478             if (it->required) {
479                 /**
480                  * WL-3210 The WRT MUST inform the user if a widget cannot be
481                  * installed because one or more required features are not
482                  * supported.
483                  */
484                 std::ostringstream os;
485                 os << "Widget cannot be installed, required feature is missing:["
486                     << DPL::ToUTF8String(it->name) << "]";
487                 if (!GlobalSettings::TestModeEnabled() && !isTizenWebApp()) {
488                     std::string label = os.str();
489                     createInstallPopup(PopupType::WIDGET_WRONG_FEATURE_INFO, label);
490                 }
491                 ThrowMsg(Exceptions::WidgetConfigFileInvalid, os.str());
492             }
493         } else {
494             newList.insert(*it);
495             featureInfo += DPL::ToUTF8String(it->name);
496             featureInfo += DPL::ToUTF8String(BR);
497         }
498     }
499     if(!data.accessInfoSet.empty()) {
500         featureInfo += WINDGET_INSTALL_NETWORK_ACCESS;
501         featureInfo += DPL::ToUTF8String(BR);
502     }
503     data.featuresList = newList;
504     if (!featureInfo.empty()) {
505         m_popupData.addWidgetInfo(DPL::FromUTF8String(featureInfo));
506     }
507
508     m_installContext.job->UpdateProgress(
509         InstallerContext::INSTALL_WIDGET_CONFIG2,
510         "Widget Config step2 Finished");
511 }
512
513 void TaskWidgetConfig::setApplicationType()
514 {
515     using namespace WrtDB;
516     WidgetRegisterInfo* widgetInfo = &(m_installContext.widgetConfig);
517     ConfigParserData* configInfo = &(widgetInfo->configInfo);
518
519     FOREACH(iterator, configInfo->nameSpaces) {
520         LogInfo("namespace = [" << *iterator << "]");
521         AppType currentAppType = APP_TYPE_UNKNOWN;
522
523         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
524             continue;
525         } else if (
526             *iterator ==
527             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
528             *iterator ==
529             ConfigurationNamespace::WacWidgetNamespaceName)
530         {
531             currentAppType = APP_TYPE_WAC20;
532         } else if (*iterator == ConfigurationNamespace::TizenWebAppNamespaceName) {
533             currentAppType = APP_TYPE_TIZENWEBAPP;
534         }
535
536         if (widgetInfo->webAppType == APP_TYPE_UNKNOWN) {
537             widgetInfo->webAppType = currentAppType;
538         } else if (widgetInfo->webAppType == currentAppType) {
539             continue;
540         } else {
541             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
542                      "Config.xml has more than one namespace");
543         }
544     }
545
546     // If there is no define, type set to WAC 2.0
547     if (widgetInfo->webAppType == APP_TYPE_UNKNOWN) {
548         widgetInfo->webAppType = APP_TYPE_WAC20;
549     }
550
551     LogInfo("type = [" << widgetInfo->webAppType.getApptypeToString() << "]");
552 }
553
554 bool TaskWidgetConfig::isFeatureAllowed(WrtDB::AppType appType,
555                                         DPL::String featureName)
556 {
557     using namespace WrtDB;
558     LogInfo("AppType = [" <<
559             WidgetType(appType).getApptypeToString() << "]");
560     LogInfo("FetureName = [" << featureName << "]");
561
562     AppType featureType = APP_TYPE_UNKNOWN;
563     const char* feature = DPL::ToUTF8String(featureName).c_str();
564     // check prefix of  feature name
565     if (strstr(feature, PluginsPrefix::TIZENPluginsPrefix) == feature) {
566         // Tizen WebApp feature
567         featureType = APP_TYPE_TIZENWEBAPP;
568     } else if (strstr(feature, PluginsPrefix::WACPluginsPrefix) == feature) {
569         // WAC 2.0 feature
570         featureType = APP_TYPE_WAC20;
571     } else if (strstr(feature, PluginsPrefix::W3CPluginsPrefix) == feature) {
572         // W3C standard feature
573         // Both WAC and TIZEN WebApp are possible to use W3C plugins
574         return true;
575     } else {
576         // unknown feature
577         // unknown feature will be checked next step
578         return true;
579     }
580
581     if (appType == featureType) {
582         return true;
583     }
584     return false;
585 }
586
587 bool TaskWidgetConfig::parseVersionString(const std::string &version,
588         long &majorVersion, long &minorVersion, long &microVersion) const
589 {
590     std::istringstream inputString(version);
591     inputString >> majorVersion;
592     if (inputString.bad() || inputString.fail()) {
593         LogWarning("Invalid minVersion format.");
594         return false;
595     }
596     inputString.get(); // skip period
597     inputString >> minorVersion;
598     if (inputString.bad() || inputString.fail()) {
599         LogWarning("Invalid minVersion format");
600         return false;
601     } else {
602         inputString.get(); // skip period
603         if (inputString.bad() || inputString.fail()) {
604             inputString >> microVersion;
605         }
606     }
607     return true;
608 }
609
610 bool TaskWidgetConfig::isMinVersionCompatible(WrtDB::AppType appType,
611         const DPL::OptionalString &widgetVersion) const
612 {
613     if (widgetVersion.IsNull() || (*widgetVersion).empty())
614     {
615         LogWarning("minVersion attribute is empty. WRT assumes platform "
616                 "supports this widget.");
617         return true;
618     }
619
620     //Parse widget version
621     long majorWidget = 0, minorWidget = 0, microWidget = 0;
622     if (!parseVersionString(DPL::ToUTF8String(*widgetVersion), majorWidget,
623             minorWidget, microWidget)) {
624         LogWarning("Invalid format of widget version string.");
625         return true;
626     }
627
628     //Parse supported version
629     long majorSupported = 0, minorSupported = 0, microSupported = 0;
630     std::string version;
631     if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
632         version = WrtDB::GlobalConfig::GetTizenVersion();
633     } else if (appType == WrtDB::AppType::APP_TYPE_WAC20) {
634         version = WrtDB::GlobalConfig::GetWACVersion();
635     } else {
636         LogWarning("Invaild AppType");
637         return false;
638     }
639
640     if (!parseVersionString(version,
641                 majorSupported, minorSupported, microSupported)) {
642         LogWarning("Invalid format of platform version string.");
643         return true;
644     }
645
646     if (majorWidget > majorSupported ||
647             (majorWidget == majorSupported && minorWidget > minorSupported) ||
648             (majorWidget == majorSupported && minorWidget == minorSupported
649                     && microWidget > microSupported))
650     {
651         LogInfo("Platform doesn't support this widget.");
652         return false;
653     }
654     return true;
655 }
656
657 bool TaskWidgetConfig::isTizenWebApp() const
658 {
659     bool ret = FALSE;
660     if (m_installContext.widgetConfig.webAppType.appType
661             == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
662         ret = TRUE;
663
664     return ret;
665 }
666
667 bool TaskWidgetConfig::parseConfigurationFileBrowser(WrtDB::ConfigParserData& configInfo,
668                                     const std::string& _currentPath, int* pErrCode)
669 {
670     ParserRunner parser;
671     Try
672     {
673         parser.Parse(_currentPath, ElementParserPtr(new
674                                                   RootParser<
675                                                       WidgetParser>(
676                                                       configInfo,
677                                                       DPL::FromUTF32String(
678                                                           L"widget"))));
679     }
680     Catch(ElementParser::Exception::Base)
681     {
682         LogError("Invalid widget configuration file!");
683         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
684         return false;
685     }
686     return true;
687 }
688
689 bool TaskWidgetConfig::parseConfigurationFileWidget(WrtDB::ConfigParserData& configInfo,
690                                     const std::string& _currentPath, int* pErrCode)
691 {
692     ParserRunner parser;
693
694     //TODO: rewrite this madness
695     std::string cfgAbsPath;
696     DIR* dir = NULL;
697     struct dirent* ptr = NULL;
698
699     dir = opendir(_currentPath.c_str());
700     if (dir == NULL) {
701         *pErrCode = WRT_ERR_UNKNOWN;
702         return false;
703     }
704     bool has_config_xml = false;
705     errno = 0;
706     while ((ptr = readdir(dir)) != NULL) { //Find configuration file, based on its name
707         if (ptr->d_type == DT_REG) {
708             if (!strcmp(ptr->d_name, WRT_WIDGET_CONFIG_FILE_NAME)) {
709                 std::string dName(ptr->d_name);
710                 WrtUtilJoinPaths(cfgAbsPath, _currentPath, dName);
711
712                 //Parse widget configuration file
713                 LogDebug("Found config: " << cfgAbsPath);
714
715                 Try
716                 {
717                     parser.Parse(cfgAbsPath, ElementParserPtr(new
718                                                               RootParser<
719                                                                   WidgetParser>(
720                                                                   configInfo,
721                                                                   DPL
722                                                                       ::
723                                                                       FromUTF32String(
724                                                                       L"widget"))));
725                 }
726                 Catch(ElementParser::Exception::Base)
727                 {
728                     LogError("Invalid widget configuration file!");
729                     //                    _rethrown_exception.Dump();
730                     *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
731                     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
732                         LogError("Failed to close dir: " << _currentPath << " with error: "
733                                 << DPL::GetErrnoString());
734                     }
735                     return false;
736                 }
737
738                 has_config_xml = true;
739                 break;
740             }
741         }
742     }
743     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
744         LogError("Failed to close dir: " << _currentPath << " with error: "
745                 << DPL::GetErrnoString());
746     }
747
748     //We must have config.xml so leaveing if we doesn't
749     if (!has_config_xml) {
750         LogError("Invalid archive");
751         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
752         return false;
753     }
754     return true;
755 }
756
757 bool TaskWidgetConfig::locateAndParseConfigurationFile(
758         const std::string& _currentPath,
759         WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
760         const std::string& baseFolder,
761         int* pErrCode)
762 {
763     using namespace WrtDB;
764
765     if (!pErrCode) {
766         return false;
767     }
768
769     ConfigParserData& configInfo = pWidgetConfigInfo.configInfo;
770
771     // check if this installation from browser, or not.
772     size_t pos = _currentPath.rfind("/");
773     std::ostringstream infoPath;
774     infoPath << _currentPath.substr(pos+1);
775
776     if (infoPath.str() != WRT_WIDGET_CONFIG_FILE_NAME) {
777         if (_currentPath.empty() || baseFolder.empty()) {
778             *pErrCode = WRT_ERR_INVALID_ARG;
779             return false;
780         }
781         // in case of general installation using wgt archive
782         if(!parseConfigurationFileWidget(configInfo, _currentPath, pErrCode))
783         {
784             return false;
785         }
786     } else {
787         // in case of browser installation
788         if(!parseConfigurationFileBrowser(configInfo, _currentPath, pErrCode))
789         {
790             return false;
791         }
792     }
793
794     if(!fillWidgetConfig(pWidgetConfigInfo, configInfo))
795     {
796         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
797         return false;
798     }
799     return true;
800 }
801
802 bool TaskWidgetConfig::fillWidgetConfig(WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
803                                         WrtDB::ConfigParserData& configInfo)
804 {
805     if (!!configInfo.widget_id) {
806         if (!pWidgetConfigInfo.guid) {
807             pWidgetConfigInfo.guid = configInfo.widget_id;
808         } else {
809             if (pWidgetConfigInfo.guid != configInfo.widget_id) {
810                 LogError("Invalid archive");
811                 return false;
812             }
813         }
814     }
815     if (!!configInfo.tizenId) {
816         if (pWidgetConfigInfo.pkgname_NOTNULL != *configInfo.tizenId) {
817             LogError("Invalid archive - Tizen ID not same error");
818             return false;
819         }
820     }
821     if (!!configInfo.version) {
822         if (!pWidgetConfigInfo.version) {
823             pWidgetConfigInfo.version = configInfo.version;
824         } else {
825             if (pWidgetConfigInfo.version != configInfo.version) {
826                 LogError("Invalid archive");
827                 return false;
828             }
829         }
830     }
831     if (!!configInfo.minVersionRequired) {
832         pWidgetConfigInfo.minVersion = configInfo.minVersionRequired;
833     } else if (!!configInfo.tizenMinVersionRequired) {
834         pWidgetConfigInfo.minVersion = configInfo.tizenMinVersionRequired;
835     }
836     return true;
837 }
838
839 void TaskWidgetConfig::processFile(const std::string& path,
840         WrtDB::WidgetRegisterInfo &widgetConfiguration)
841 {
842     int pErrCode;
843
844     if (!locateAndParseConfigurationFile(path, widgetConfiguration,
845                                          DEFAULT_LANGUAGE, &pErrCode)) {
846         LogWarning("Widget archive: Failed while parsing config file");
847         ThrowMsg(Exception::ConfigParseFailed, path);
848     }
849 }
850
851 } //namespace WidgetInstall
852 } //namespace Jobs