842314485554eb7794e854c97c6ec712dbc496e4
[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
85     if (!GlobalSettings::TestModeEnabled() && !m_installContext.m_quiet) {
86         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallationAfterVerifyFeatures);
87         AddStep(&TaskWidgetConfig::StepShowWidgetInfo);
88         AddStep(&TaskWidgetConfig::StepCancelWidgetInstallation);
89         AddStep(&TaskWidgetConfig::StepCheckMinVersionInfo);
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         std::string label = WIDGET_NOT_COMPATIBLE + QUESTION;
430         createInstallPopup(PopupType::WIDGET_MIN_VERSION, label);
431     }
432
433     m_installContext.job->UpdateProgress(
434             InstallerContext::INSTALL_WIDGET_CONFIG2,
435             "Check MinVersion Finished");
436 }
437
438 void TaskWidgetConfig::StepVerifyFeatures()
439 {
440     using namespace WrtDB;
441     ConfigParserData &data = m_installContext.widgetConfig.configInfo;
442     ConfigParserData::FeaturesList list = data.featuresList;
443     ConfigParserData::FeaturesList newList;
444
445     //in case of tests, this variable is unused
446     std::string featureInfo;
447     FOREACH(it, list)
448     {
449         // check feature vender for permission
450         // WAC, TIZEN WebApp cannot use other feature
451
452         if (!isFeatureAllowed(m_installContext.widgetConfig.webAppType.appType,
453                               it->name))
454         {
455             LogInfo("This application type not allowed to use this feature");
456             ThrowMsg(
457                 Exceptions::WidgetConfigFileInvalid,
458                 "This app type [" <<
459                 m_installContext.widgetConfig.webAppType.getApptypeToString() <<
460                 "] cannot be allowed to use [" <<
461                 DPL::ToUTF8String(it->name) + "] feature");
462         }
463         if (!WrtDB::FeatureDAOReadOnly::isFeatureInstalled(
464                 DPL::ToUTF8String(it->name))) {
465             LogWarning("Feature not found. Checking if required :[" <<
466                        DPL::ToUTF8String(it->name) << "]");
467
468             if (it->required) {
469                 /**
470                  * WL-3210 The WRT MUST inform the user if a widget cannot be
471                  * installed because one or more required features are not
472                  * supported.
473                  */
474                 std::ostringstream os;
475                 os << "Widget cannot be installed, required feature is missing:["
476                     << DPL::ToUTF8String(it->name) << "]";
477                 if (!GlobalSettings::TestModeEnabled() && !isTizenWebApp()) {
478                     std::string label = os.str();
479                     createInstallPopup(PopupType::WIDGET_WRONG_FEATURE_INFO, label);
480                 }
481                 ThrowMsg(Exceptions::WidgetConfigFileInvalid, os.str());
482             }
483         } else {
484             newList.insert(*it);
485             featureInfo += DPL::ToUTF8String(it->name);
486             featureInfo += DPL::ToUTF8String(BR);
487         }
488     }
489     if(!data.accessInfoSet.empty()) {
490         featureInfo += WINDGET_INSTALL_NETWORK_ACCESS;
491         featureInfo += DPL::ToUTF8String(BR);
492     }
493     data.featuresList = newList;
494     if (!featureInfo.empty()) {
495         m_popupData.addWidgetInfo(DPL::FromUTF8String(featureInfo));
496     }
497
498     m_installContext.job->UpdateProgress(
499         InstallerContext::INSTALL_WIDGET_CONFIG2,
500         "Widget Config step2 Finished");
501 }
502
503 void TaskWidgetConfig::setApplicationType()
504 {
505     using namespace WrtDB;
506     WidgetRegisterInfo* widgetInfo = &(m_installContext.widgetConfig);
507     ConfigParserData* configInfo = &(widgetInfo->configInfo);
508
509     FOREACH(iterator, configInfo->nameSpaces) {
510         LogInfo("namespace = [" << *iterator << "]");
511         AppType currentAppType = APP_TYPE_UNKNOWN;
512
513         if (*iterator == ConfigurationNamespace::W3CWidgetNamespaceName) {
514             continue;
515         } else if (
516             *iterator ==
517             ConfigurationNamespace::WacWidgetNamespaceNameForLinkElement ||
518             *iterator ==
519             ConfigurationNamespace::WacWidgetNamespaceName)
520         {
521             currentAppType = APP_TYPE_WAC20;
522         } else if (*iterator == ConfigurationNamespace::TizenWebAppNamespaceName) {
523             currentAppType = APP_TYPE_TIZENWEBAPP;
524         }
525
526         if (widgetInfo->webAppType == APP_TYPE_UNKNOWN) {
527             widgetInfo->webAppType = currentAppType;
528         } else if (widgetInfo->webAppType == currentAppType) {
529             continue;
530         } else {
531             ThrowMsg(Exceptions::WidgetConfigFileInvalid,
532                      "Config.xml has more than one namespace");
533         }
534     }
535
536     // If there is no define, type set to WAC 2.0
537     if (widgetInfo->webAppType == APP_TYPE_UNKNOWN) {
538         widgetInfo->webAppType = APP_TYPE_WAC20;
539     }
540
541     LogInfo("type = [" << widgetInfo->webAppType.getApptypeToString() << "]");
542 }
543
544 bool TaskWidgetConfig::isFeatureAllowed(WrtDB::AppType appType,
545                                         DPL::String featureName)
546 {
547     using namespace WrtDB;
548     LogInfo("AppType = [" <<
549             WidgetType(appType).getApptypeToString() << "]");
550     LogInfo("FetureName = [" << featureName << "]");
551
552     AppType featureType = APP_TYPE_UNKNOWN;
553     const char* feature = DPL::ToUTF8String(featureName).c_str();
554     // check prefix of  feature name
555     if (strstr(feature, PluginsPrefix::TIZENPluginsPrefix) == feature) {
556         // Tizen WebApp feature
557         featureType = APP_TYPE_TIZENWEBAPP;
558     } else if (strstr(feature, PluginsPrefix::WACPluginsPrefix) == feature) {
559         // WAC 2.0 feature
560         featureType = APP_TYPE_WAC20;
561     } else if (strstr(feature, PluginsPrefix::W3CPluginsPrefix) == feature) {
562         // W3C standard feature
563         // Both WAC and TIZEN WebApp are possible to use W3C plugins
564         return true;
565     } else {
566         // unknown feature
567         // unknown feature will be checked next step
568         return true;
569     }
570
571     if (appType == featureType) {
572         return true;
573     }
574     return false;
575 }
576
577 bool TaskWidgetConfig::parseVersionString(const std::string &version,
578         long &majorVersion, long &minorVersion, long &microVersion) const
579 {
580     std::istringstream inputString(version);
581     inputString >> majorVersion;
582     if (inputString.bad() || inputString.fail()) {
583         LogWarning("Invalid minVersion format.");
584         return false;
585     }
586     inputString.get(); // skip period
587     inputString >> minorVersion;
588     if (inputString.bad() || inputString.fail()) {
589         LogWarning("Invalid minVersion format");
590         return false;
591     } else {
592         inputString.get(); // skip period
593         if (inputString.bad() || inputString.fail()) {
594             inputString >> microVersion;
595         }
596     }
597     return true;
598 }
599
600 bool TaskWidgetConfig::isMinVersionCompatible(WrtDB::AppType appType,
601         const DPL::OptionalString &widgetVersion) const
602 {
603     if (widgetVersion.IsNull() || (*widgetVersion).empty())
604     {
605         LogWarning("minVersion attribute is empty. WRT assumes platform "
606                 "supports this widget.");
607         return true;
608     }
609
610     //Parse widget version
611     long majorWidget = 0, minorWidget = 0, microWidget = 0;
612     if (!parseVersionString(DPL::ToUTF8String(*widgetVersion), majorWidget,
613             minorWidget, microWidget)) {
614         LogWarning("Invalid format of widget version string.");
615         return true;
616     }
617
618     //Parse supported version
619     long majorSupported = 0, minorSupported = 0, microSupported = 0;
620     std::string version;
621     if (appType == WrtDB::AppType::APP_TYPE_TIZENWEBAPP) {
622         version = WrtDB::GlobalConfig::GetTizenVersion();
623     } else if (appType == WrtDB::AppType::APP_TYPE_WAC20) {
624         version = WrtDB::GlobalConfig::GetWACVersion();
625     } else {
626         LogWarning("Invaild AppType");
627         return false;
628     }
629
630     if (!parseVersionString(version,
631                 majorSupported, minorSupported, microSupported)) {
632         LogWarning("Invalid format of WAC version string.");
633         return true;
634     }
635
636     if (majorWidget > majorSupported ||
637             minorWidget > minorSupported ||
638             microWidget > microSupported) {
639         LogInfo("Platform doesn't support this widget.");
640         return false;
641     }
642     return true;
643 }
644
645 bool TaskWidgetConfig::isTizenWebApp() const
646 {
647     bool ret = FALSE;
648     if (m_installContext.widgetConfig.webAppType.appType
649             == WrtDB::AppType::APP_TYPE_TIZENWEBAPP)
650         ret = TRUE;
651
652     return ret;
653 }
654
655 bool TaskWidgetConfig::parseConfigurationFileBrowser(WrtDB::ConfigParserData& configInfo,
656                                     const std::string& _currentPath, int* pErrCode)
657 {
658     ParserRunner parser;
659     Try
660     {
661         parser.Parse(_currentPath, ElementParserPtr(new
662                                                   RootParser<
663                                                       WidgetParser>(
664                                                       configInfo,
665                                                       DPL::FromUTF32String(
666                                                           L"widget"))));
667     }
668     Catch(ElementParser::Exception::Base)
669     {
670         LogError("Invalid widget configuration file!");
671         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
672         return false;
673     }
674     return true;
675 }
676
677 bool TaskWidgetConfig::parseConfigurationFileWidget(WrtDB::ConfigParserData& configInfo,
678                                     const std::string& _currentPath, int* pErrCode)
679 {
680     ParserRunner parser;
681
682     //TODO: rewrite this madness
683     std::string cfgAbsPath;
684     DIR* dir = NULL;
685     struct dirent* ptr = NULL;
686
687     dir = opendir(_currentPath.c_str());
688     if (dir == NULL) {
689         *pErrCode = WRT_ERR_UNKNOWN;
690         return false;
691     }
692     bool has_config_xml = false;
693     errno = 0;
694     while ((ptr = readdir(dir)) != NULL) { //Find configuration file, based on its name
695         if (ptr->d_type == DT_REG) {
696             if (!strcmp(ptr->d_name, WRT_WIDGET_CONFIG_FILE_NAME)) {
697                 std::string dName(ptr->d_name);
698                 WrtUtilJoinPaths(cfgAbsPath, _currentPath, dName);
699
700                 //Parse widget configuration file
701                 LogDebug("Found config: " << cfgAbsPath);
702
703                 Try
704                 {
705                     parser.Parse(cfgAbsPath, ElementParserPtr(new
706                                                               RootParser<
707                                                                   WidgetParser>(
708                                                                   configInfo,
709                                                                   DPL
710                                                                       ::
711                                                                       FromUTF32String(
712                                                                       L"widget"))));
713                 }
714                 Catch(ElementParser::Exception::Base)
715                 {
716                     LogError("Invalid widget configuration file!");
717                     //                    _rethrown_exception.Dump();
718                     *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
719                     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
720                         LogError("Failed to close dir: " << _currentPath << " with error: "
721                                 << DPL::GetErrnoString());
722                     }
723                     return false;
724                 }
725
726                 has_config_xml = true;
727                 break;
728             }
729         }
730     }
731     if (-1 == TEMP_FAILURE_RETRY(closedir(dir))) {
732         LogError("Failed to close dir: " << _currentPath << " with error: "
733                 << DPL::GetErrnoString());
734     }
735
736     //We must have config.xml so leaveing if we doesn't
737     if (!has_config_xml) {
738         LogError("Invalid archive");
739         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
740         return false;
741     }
742     return true;
743 }
744
745 bool TaskWidgetConfig::locateAndParseConfigurationFile(
746         const std::string& _currentPath,
747         WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
748         const std::string& baseFolder,
749         int* pErrCode)
750 {
751     using namespace WrtDB;
752
753     if (!pErrCode) {
754         return false;
755     }
756
757     ConfigParserData& configInfo = pWidgetConfigInfo.configInfo;
758
759     // check if this installation from browser, or not.
760     size_t pos = _currentPath.rfind("/");
761     std::ostringstream infoPath;
762     infoPath << _currentPath.substr(pos+1);
763
764     if (infoPath.str() != WRT_WIDGET_CONFIG_FILE_NAME) {
765         if (_currentPath.empty() || baseFolder.empty()) {
766             *pErrCode = WRT_ERR_INVALID_ARG;
767             return false;
768         }
769         // in case of general installation using wgt archive
770         if(!parseConfigurationFileWidget(configInfo, _currentPath, pErrCode))
771         {
772             return false;
773         }
774     } else {
775         // in case of browser installation
776         if(!parseConfigurationFileBrowser(configInfo, _currentPath, pErrCode))
777         {
778             return false;
779         }
780     }
781
782     if(!fillWidgetConfig(pWidgetConfigInfo, configInfo))
783     {
784         *pErrCode = WRT_WM_ERR_INVALID_ARCHIVE;
785         return false;
786     }
787     return true;
788 }
789
790 bool TaskWidgetConfig::fillWidgetConfig(WrtDB::WidgetRegisterInfo& pWidgetConfigInfo,
791                                         WrtDB::ConfigParserData& configInfo)
792 {
793     if (!!configInfo.widget_id) {
794         if (!pWidgetConfigInfo.guid) {
795             pWidgetConfigInfo.guid = configInfo.widget_id;
796         } else {
797             if (pWidgetConfigInfo.guid != configInfo.widget_id) {
798                 LogError("Invalid archive");
799                 return false;
800             }
801         }
802     }
803     if (!!configInfo.tizenId) {
804         if (!pWidgetConfigInfo.pkgname) {
805             pWidgetConfigInfo.pkgname = configInfo.tizenId;
806         } else {
807             if (pWidgetConfigInfo.pkgname != configInfo.tizenId) {
808                 LogError("Invalid archive - Tizen ID not same error");
809                 return false;
810             }
811         }
812     }
813     if (!!configInfo.version) {
814         if (!pWidgetConfigInfo.version) {
815             pWidgetConfigInfo.version = configInfo.version;
816         } else {
817             if (pWidgetConfigInfo.version != configInfo.version) {
818                 LogError("Invalid archive");
819                 return false;
820             }
821         }
822     }
823     if (!!configInfo.minVersionRequired) {
824         pWidgetConfigInfo.minVersion = configInfo.minVersionRequired;
825     } else if (!!configInfo.tizenMinVersionRequired) {
826         pWidgetConfigInfo.minVersion = configInfo.tizenMinVersionRequired;
827     }
828     return true;
829 }
830
831 void TaskWidgetConfig::processFile(const std::string& path,
832         WrtDB::WidgetRegisterInfo &widgetConfiguration)
833 {
834     int pErrCode;
835
836     if (!locateAndParseConfigurationFile(path, widgetConfiguration,
837                                          DEFAULT_LANGUAGE, &pErrCode)) {
838         LogWarning("Widget archive: Failed while parsing config file");
839         ThrowMsg(Exception::ConfigParseFailed, path);
840     }
841 }
842
843 } //namespace WidgetInstall
844 } //namespace Jobs