PageRenderTime 73ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/sondage/admin/remotecontrol/lsrc.helper.php

https://bitbucket.org/bontiv/insomnia
PHP | 2460 lines | 1837 code | 257 blank | 366 comment | 219 complexity | c7a88cb41d6052a07b3daa35dad8658a MD5 | raw file
Possible License(s): Apache-2.0, LGPL-3.0, LGPL-2.1, GPL-3.0, BSD-3-Clause, GPL-2.0
  1. <?php
  2. /*
  3. * LimeSurvey
  4. * Copyright (C) 2007 The LimeSurvey Project Team / Carsten Schmitz
  5. * All rights reserved.
  6. * License: GNU/GPL License v2 or later, see LICENSE.php
  7. * LimeSurvey is free software. This version may have been modified pursuant
  8. * to the GNU General Public License, and as distributed it includes or
  9. * is derivative of works licensed under the GNU General Public License or
  10. * other free or open source software licenses.
  11. * See COPYRIGHT.php for copyright notices and details.
  12. *
  13. * $Id: lsrc.helper.php 9656 2011-01-07 20:48:39Z c_schmitz $
  14. *
  15. */
  16. /**
  17. * @author Wahrendorff
  18. *
  19. */
  20. class LsrcHelper {
  21. /**
  22. * simple debug function to make life a bit easier
  23. *
  24. * @param string $text
  25. */
  26. function debugLsrc($text)
  27. {
  28. include("lsrc.config.php");
  29. if($lsrcDebug)
  30. {
  31. error_log("\n".date("Y-m-d H:i:s")." ".$text, 3 , $lsrcDebugLog);
  32. }
  33. return;
  34. }
  35. /**
  36. * function to get the id of the surveyowner
  37. *
  38. * @param unknown_type $iVid
  39. * @return unknown
  40. */
  41. function getSurveyOwner($iVid)
  42. {
  43. global $connect ;
  44. global $dbprefix ;
  45. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  46. include("lsrc.config.php");
  47. //$this= new LsrcHelper();
  48. if($this->surveyExists($iVid))
  49. {
  50. $query2num = "SELECT owner_id FROM {$dbprefix}surveys WHERE sid=".sanitize_int($iVid)."";
  51. $rs = db_execute_assoc($query2num);
  52. $field=$rs->FetchRow();
  53. return $field['owner_id'];
  54. }else{return false;}
  55. }
  56. /**
  57. * This function changes data in LS-DB, its very sensitive, because every table can be changed.
  58. *
  59. * @param unknown_type $table
  60. * @param unknown_type $key
  61. * @param unknown_type $value
  62. * @param unknown_type $where
  63. * @return String
  64. */
  65. function changeTable($table, $key, $value, $where, $mode='0')//XXX
  66. {//be aware that this function may be a security risk
  67. global $connect ;
  68. global $dbprefix ;
  69. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  70. include("lsrc.config.php");
  71. if($mode=='' || !isset($mode) || $mode=='0')
  72. {
  73. $where = str_replace("\\","",$where);
  74. $query2num = "SELECT {$key} FROM {$dbprefix}{$table} WHERE {$where}";
  75. $rs = db_execute_assoc($query2num);
  76. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ($query2num)");
  77. $query2update = "update ".$dbprefix.$table." set ".$key."='".$value."' where ".$where."";
  78. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ($query2update)");
  79. if($connect->Execute($query2update)){
  80. return $rs->RecordCount()." Rows changed";
  81. }
  82. else{
  83. return "nothing changed";
  84. }
  85. }
  86. if($mode==1 || $mode=='1')
  87. {
  88. $query2insert = "INSERT INTO {$dbprefix}{$table} ({$key}) VALUES ({$value});";
  89. $this->debugLsrc("wir sind in Line ".__LINE__.", inserting ($query2insert)");
  90. if($connect->Execute($query2insert))
  91. {
  92. $this->debugLsrc("wir sind in Line ".__LINE__.", inserting OK");
  93. return true;
  94. }
  95. else
  96. {
  97. return false;
  98. }
  99. }
  100. }
  101. /**
  102. *
  103. * Enter description here...
  104. * @param $surveyid
  105. * @param $type
  106. * @param $maxLsrcEmails
  107. * @return unknown_type
  108. */
  109. function emailSender($surveyid, $type, $maxLsrcEmails='') //XXX
  110. {
  111. global $publicurl,$maxemails;
  112. global $connect,$sitename ;
  113. global $dbprefix ;
  114. $surveyid = sanitize_int($surveyid);
  115. include("lsrc.config.php");
  116. // wenn maxmails ber den lsrc gegeben wird das nutzen, ansonsten die default werte aus der config.php
  117. if($maxLsrcEmails!='')
  118. $maxemails = $maxLsrcEmails;
  119. switch ($type){
  120. case "custom":
  121. break;
  122. case "invite":
  123. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START invite ");
  124. if(isset($surveyid) && getEmailFormat($surveyid) == 'html')
  125. {
  126. $ishtml=true;
  127. }
  128. else
  129. {
  130. $ishtml=false;
  131. }
  132. //$tokenoutput .= ("Sending Invitations");
  133. //if (isset($tokenid)) {$tokenoutput .= " (".("Sending to Token ID").":&nbsp;{$tokenid})";}
  134. //$tokenoutput .= "\n";
  135. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $surveyid, $type");
  136. // Texte für Mails aus der Datenbank holen und in die POST Dinger schreiben. Nicht schön aber praktikabel
  137. $sql = "SELECT surveyls_language, surveyls_email_invite_subj, surveyls_email_invite ".
  138. "FROM {$dbprefix}surveys_languagesettings ".
  139. "WHERE surveyls_survey_id = ".$surveyid." ";
  140. //GET SURVEY DETAILS
  141. $thissurvey=getSurveyInfo($surveyid);
  142. // $connect->SetFetchMode(ADODB_FETCH_ASSOC);
  143. // $sqlResult=$connect->Execute($sql);
  144. $sqlResult = db_execute_assoc($sql);
  145. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  146. while($languageRow = $sqlResult->FetchRow())
  147. {
  148. $_POST['message_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_invite'];
  149. $_POST['subject_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_invite_subj'];
  150. }
  151. // if (isset($_POST['bypassbademails']) && $_POST['bypassbademails'] == 'Y')
  152. // {
  153. // $SQLemailstatuscondition = " AND emailstatus = 'OK'";
  154. // }
  155. // else
  156. // {
  157. // $SQLemailstatuscondition = "";
  158. // }
  159. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  160. $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND emailstatus = 'OK' ";
  161. if (isset($tokenid)) {$ctquery .= " AND tid='{$tokenid}'";}
  162. //$tokenoutput .= "<!-- ctquery: $ctquery -->\n";
  163. $ctresult = $connect->Execute($ctquery);
  164. $ctcount = $ctresult->RecordCount();
  165. $ctfieldcount = $ctresult->FieldCount();
  166. $emquery = "SELECT * ";
  167. //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";}
  168. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  169. $emquery .= " FROM ".db_table_name("tokens_{$surveyid}")." WHERE ((completed ='N') or (completed='')) AND ((sent ='N') or (sent='')) AND emailstatus = 'OK' ";
  170. if (isset($tokenid)) {$emquery .= " and tid='{$tokenid}'";}
  171. //$tokenoutput .= "\n\n<!-- emquery: $emquery -->\n\n";
  172. $emresult = db_select_limit_assoc($emquery,$maxemails);
  173. $emcount = $emresult->RecordCount();
  174. //$tokenoutput .= "<table width='500px' align='center' >\n"
  175. ////."\t<tr>\n"
  176. //."\t\t<td><font size='1'>\n";
  177. $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid);
  178. $baselanguage = GetBaseLanguageFromSurveyID($surveyid);
  179. array_unshift($surveylangs,$baselanguage);
  180. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  181. foreach ($surveylangs as $language)
  182. {
  183. $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]);
  184. $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]);
  185. if ($ishtml) $_POST['message_'.$language] = html_entity_decode($_POST['message_'.$language], ENT_QUOTES, $emailcharset);
  186. }
  187. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  188. if ($emcount > 0)
  189. {
  190. $mailsSend = 0;
  191. while ($emrow = $emresult->FetchRow())
  192. {
  193. $c=1;
  194. unset($fieldsarray);
  195. $to = $emrow['email'];
  196. $fieldsarray["{EMAIL}"]=$emrow['email'];
  197. $fieldsarray["{FIRSTNAME}"]=$emrow['firstname'];
  198. $fieldsarray["{LASTNAME}"]=$emrow['lastname'];
  199. $fieldsarray["{TOKEN}"]=$emrow['token'];
  200. $fieldsarray["{LANGUAGE}"]=$emrow['language'];
  201. while(isset($emrow["attribute_$c"]))
  202. {
  203. $fieldsarray["{ATTRIBUTE_$c}"]=$emrow["attribute_$c"];
  204. ++$c;
  205. }
  206. $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname'];
  207. $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
  208. $fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
  209. $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
  210. $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"];
  211. $emrow['language']=trim($emrow['language']);
  212. if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default
  213. $found = array_search($emrow['language'], $surveylangs);
  214. if ($found==false) {$emrow['language']=$baselanguage;}
  215. $from = $thissurvey['adminemail'];
  216. if ($ishtml === false)
  217. {
  218. if ( $modrewrite )
  219. {
  220. $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}";
  221. }
  222. else
  223. {
  224. $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}";
  225. }
  226. }
  227. else
  228. {
  229. if ( $modrewrite )
  230. {
  231. $fieldsarray["{SURVEYURL}"]="<a href='$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}'>".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}")."</a>";
  232. }
  233. else
  234. {
  235. $fieldsarray["{SURVEYURL}"]="<a href='$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}'>".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}")."</a>";
  236. }
  237. }
  238. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  239. $modsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray);
  240. $modmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray);
  241. if (SendEmailMessage($modmessage, $modsubject, $to , $from, $sitename, $ishtml, getBounceEmail($surveyid)))
  242. {
  243. // Put date into sent
  244. //$timeadjust = 0;
  245. $today = date("Y-m-d H:i");
  246. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite Today:".$today);
  247. $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n"
  248. ."SET sent='$today' WHERE tid={$emrow['tid']}";
  249. //
  250. $uderesult = $connect->Execute($udequery);
  251. $mailsSend++;
  252. //$tokenoutput .= "[".("Invitation sent to:")."{$emrow['firstname']} {$emrow['lastname']} ($to)]\n";
  253. }
  254. else
  255. {
  256. //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray);
  257. if($n==1)
  258. $failedAddresses .= ",".$to;
  259. else
  260. {
  261. $failedAddresses = $to;
  262. $n=1;
  263. }
  264. }
  265. }
  266. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  267. if ($ctcount > $emcount)
  268. {
  269. $lefttosend = $ctcount-$maxemails;
  270. }else{$lefttosend = 0;}
  271. }
  272. else
  273. {
  274. return "No Mails to send";
  275. }
  276. if($maxemails>0 && $maxemails!='')
  277. {
  278. $returnValue = "".$mailsSend." Mails send. ".$lefttosend." Mails left to send";
  279. if(isset($failedAddresses))
  280. $returnValue .= "\nCould not send to: ".$failedAddresses;
  281. return $returnValue;
  282. }
  283. if(isset($mailsSend))
  284. {
  285. $returnValue = "".$mailsSend." Mails send. ";
  286. if(isset($failedAddresses))
  287. $returnValue .= "\nCould not send to: ".$failedAddresses;
  288. return $returnValue;
  289. }
  290. break;
  291. case "remind":
  292. // XXX:
  293. // TODO:
  294. // if (!isset($_POST['ok']) || !$_POST['ok'])
  295. // {
  296. /*
  297. * look if there were reminders send in the past, and if some tokens got lesser reminders than others
  298. *
  299. * - if so: send reminders to the unremindet participants until they got the same remindcount than the others
  300. * - if not: send reminders normally
  301. */
  302. $remSQL = "SELECT tid, remindercount "
  303. . "FROM ".db_table_name("tokens_{$surveyid}")." "
  304. . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' "
  305. . "ORDER BY remindercount desc LIMIT 1";
  306. $this->debugLsrc("Executing SQL: ".$remSQL);
  307. $remResult = db_execute_assoc($remSQL);
  308. $remRow = $remResult->FetchRow();
  309. /* Get the reminder count from the row, if we have a row. If
  310. * we don't have a row then we set reminderCount to 0 to prevent
  311. * queries down below from bombing out. */
  312. $reminderCount = $remRow['remindercount'];
  313. if(empty($reminderCount)) {
  314. $this->debugLsrc("There are no reminders to send.");
  315. $reminderCount = 0;
  316. }
  317. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind ".$remRow['tid']."; ".$reminderCount." ");
  318. $sendOnlySQL = "SELECT tid, remindercount "
  319. . "FROM ".db_table_name("tokens_{$surveyid}")." "
  320. . "WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' AND remindercount < ".$reminderCount." "
  321. . "ORDER BY tid asc LIMIT 1";
  322. $this->debugLsrc("Executing SQL: ".$sendOnlySQL);
  323. if($sendOnlyResult->RecordCount()>0)
  324. {
  325. $sendOnlyRow = $sendOnlyResult->FetchRow();
  326. $starttokenid = $sendOnlyRow['tid'];
  327. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", remind ".$sendOnlyRow['tid']."; ".$sendOnlyRow['remindercount']." ");
  328. }
  329. if(isset($surveyid) && getEmailFormat($surveyid) == 'html')
  330. {
  331. $ishtml=true;
  332. }
  333. else
  334. {
  335. $ishtml=false;
  336. }
  337. //GET SURVEY DETAILS
  338. $thissurvey=getSurveyInfo($surveyid);
  339. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $surveyid, $type");
  340. // Texte für Mails aus der Datenbank holen.
  341. $sql = "SELECT surveyls_language, surveyls_email_remind_subj, surveyls_email_remind ".
  342. "FROM {$dbprefix}surveys_languagesettings ".
  343. "WHERE surveyls_survey_id = ".$surveyid." ";
  344. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", invite ");
  345. $sqlResult = db_execute_assoc($sql);
  346. while($languageRow = $sqlResult->FetchRow())
  347. {
  348. $_POST['message_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_remind'];
  349. $_POST['subject_'.$languageRow['surveyls_language']] = $languageRow['surveyls_email_remind_subj'];
  350. }
  351. //$tokenoutput .= ("Sending Reminders")."\n";
  352. $surveylangs = GetAdditionalLanguagesFromSurveyID($surveyid);
  353. $baselanguage = GetBaseLanguageFromSurveyID($surveyid);
  354. array_unshift($surveylangs,$baselanguage);
  355. foreach ($surveylangs as $language)
  356. {
  357. $_POST['message_'.$language]=auto_unescape($_POST['message_'.$language]);
  358. $_POST['subject_'.$language]=auto_unescape($_POST['subject_'.$language]);
  359. }
  360. $SQLemailstatuscondition = " AND emailstatus = 'OK'";
  361. if (isset($_POST['maxremindercount']) &&
  362. $_POST['maxremindercount'] != '' &&
  363. intval($_POST['maxremindercount']) != 0)
  364. {
  365. $SQLremindercountcondition = " AND remindercount < ".intval($_POST['maxremindercount']);
  366. }
  367. else
  368. {
  369. $SQLremindercountcondition = "";
  370. }
  371. if (isset($_POST['minreminderdelay']) &&
  372. $_POST['minreminderdelay'] != '' &&
  373. intval($_POST['minreminderdelay']) != 0)
  374. {
  375. // $_POST['minreminderdelay'] in days (86400 seconds per day)
  376. $compareddate = date_shift(date("Y-m-d H:i:s",time() - 86400 * intval($_POST['minreminderdelay'])),
  377. "Y-m-d H:i",$timeadjust);
  378. $SQLreminderdelaycondition = " AND ( "
  379. . " (remindersent = 'N' AND sent < '".$compareddate."') "
  380. . " OR "
  381. . " (remindersent < '".$compareddate."'))";
  382. }
  383. else
  384. {
  385. $SQLreminderdelaycondition = "";
  386. }
  387. $ctquery = "SELECT * FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed ='N' or completed ='') AND sent<>'' AND sent<>'N' AND token <>'' AND email <> '' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition";
  388. if (isset($starttokenid)) {$ctquery .= " AND tid >= '{$starttokenid}'";}
  389. // if (isset($tokenid) && $tokenid) {$ctquery .= " AND tid = '{$tokenid}'";}
  390. // //$tokenoutput .= "<!-- ctquery: $ctquery -->\n";
  391. $ctresult = $connect->Execute($ctquery) or $this->debugLsrc ("Database error!\n" . $connect->ErrorMsg());
  392. $ctcount = $ctresult->RecordCount();
  393. $ctfieldcount = $ctresult->FieldCount();
  394. $emquery = "SELECT * ";
  395. //if ($ctfieldcount > 7) {$emquery .= ", attribute_1, attribute_2";}
  396. // TLR change to put date into sent
  397. $emquery .= " FROM ".db_table_name("tokens_{$surveyid}")." WHERE (completed = 'N' or completed = '') AND sent <> 'N' and sent <>'' AND token <>'' AND EMAIL <>'' $SQLemailstatuscondition $SQLremindercountcondition $SQLreminderdelaycondition";
  398. if (isset($starttokenid)) {$emquery .= " AND tid >= '{$starttokenid}'";}
  399. if (isset($tokenid) && $tokenid) {$emquery .= " AND tid = '{$tokenid}'";}
  400. $emquery .= " ORDER BY tid ";
  401. $emresult = db_select_limit_assoc($emquery, $maxemails);
  402. //$emresult = db_execute_assoc($emquery);
  403. $emcount = $emresult->RecordCount();
  404. if ($emcount > 0)
  405. {
  406. while ($emrow = $emresult->FetchRow())
  407. {
  408. $c=1;
  409. unset($fieldsarray);
  410. $to = $emrow['email'];
  411. $fieldsarray["{EMAIL}"]=$emrow['email'];
  412. $fieldsarray["{FIRSTNAME}"]=$emrow['firstname'];
  413. $fieldsarray["{LASTNAME}"]=$emrow['lastname'];
  414. $fieldsarray["{TOKEN}"]=$emrow['token'];
  415. $fieldsarray["{LANGUAGE}"]=$emrow['language'];
  416. while(isset($emrow["attribute_$c"]))
  417. {
  418. $fieldsarray["{ATTRIBUTE_$c}"]=$emrow["attribute_$c"];
  419. ++$c;
  420. }
  421. $fieldsarray["{ADMINNAME}"]= $thissurvey['adminname'];
  422. $fieldsarray["{ADMINEMAIL}"]=$thissurvey['adminemail'];
  423. $fieldsarray["{SURVEYNAME}"]=$thissurvey['name'];
  424. $fieldsarray["{SURVEYDESCRIPTION}"]=$thissurvey['description'];
  425. $fieldsarray["{EXPIRY}"]=$thissurvey["expiry"];
  426. $emrow['language']=trim($emrow['language']);
  427. if ($emrow['language']=='') {$emrow['language']=$baselanguage;} //if language is not give use default
  428. if(!in_array($emrow['language'], $surveylangs)) {$emrow['language']=$baselanguage;} // if given language is not available use default
  429. $found = array_search($emrow['language'], $surveylangs);
  430. if ($found==false) {$emrow['language']=$baselanguage;}
  431. $from = $thissurvey['adminemail'];
  432. if (getEmailFormat($surveyid) == 'html')
  433. {
  434. $ishtml=true;
  435. }
  436. else
  437. {
  438. $ishtml=false;
  439. }
  440. if ($ishtml == false)
  441. {
  442. if ( $modrewrite )
  443. {
  444. $fieldsarray["{SURVEYURL}"]="$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}";
  445. }
  446. else
  447. {
  448. $fieldsarray["{SURVEYURL}"]="$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}";
  449. }
  450. }
  451. else
  452. {
  453. if ( $modrewrite )
  454. {
  455. $fieldsarray["{SURVEYURL}"]="<a href='$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}'>".htmlspecialchars("$publicurl/$surveyid/lang-".trim($emrow['language'])."/tk-{$emrow['token']}")."</a>";
  456. }
  457. else
  458. {
  459. $fieldsarray["{SURVEYURL}"]="<a href='$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}'>".htmlspecialchars("$publicurl/index.php?lang=".trim($emrow['language'])."&sid=$surveyid&token={$emrow['token']}")."</a>";
  460. $_POST['message_'.$emrow['language']] = html_entity_decode($_POST['message_'.$emrow['language']], ENT_QUOTES, $emailcharset);
  461. }
  462. }
  463. $msgsubject=Replacefields($_POST['subject_'.$emrow['language']], $fieldsarray);
  464. $sendmessage=Replacefields($_POST['message_'.$emrow['language']], $fieldsarray);
  465. if (SendEmailMessage($sendmessage, $msgsubject, $to, $from, $sitename, $ishtml, getBounceEmail($surveyid)))
  466. {
  467. // Put date into remindersent
  468. $today = date("Y-m-d H:i");
  469. $udequery = "UPDATE ".db_table_name("tokens_{$surveyid}")."\n"
  470. ."SET remindersent='$today',remindercount = remindercount+1 WHERE tid={$emrow['tid']}";
  471. //
  472. $uderesult = $connect->Execute($udequery) or $this->debugLsrc ("Could not update tokens$udequery".$connect->ErrorMsg());
  473. //orig: $tokenoutput .= "\t\t\t({$emrow['tid']})[".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']}]\n";
  474. //$tokenoutput .= "\t\t\t({$emrow['tid']}) [".("Reminder sent to:")." {$emrow['firstname']} {$emrow['lastname']} ($to)]\n";
  475. $mailsSend++;
  476. }
  477. else
  478. {
  479. //$tokenoutput .= ReplaceFields(("Email to {FIRSTNAME} {LASTNAME} ({EMAIL}) failed. Error Message:")." ".$maildebug."", $fieldsarray);
  480. if($n==1)
  481. $failedAddresses .= ",".$to;
  482. else
  483. {
  484. $failedAddresses = $to;
  485. $n=1;
  486. }
  487. }
  488. //$lasttid = $emrow['tid'];
  489. }
  490. if ($ctcount > $emcount)
  491. {
  492. $lefttosend = $ctcount-$maxemails;
  493. }else{$lefttosend = 0;}
  494. }
  495. else
  496. {
  497. return "No Reminders to send";
  498. }
  499. if($maxemails>0)
  500. {
  501. $returnValue = "".$mailsSend." Reminders send. ".$lefttosend." Reminders left to send";
  502. if(isset($failedAddresses))
  503. $returnValue .= "\nCould not send to: ".$failedAddresses;
  504. return $returnValue;
  505. }
  506. if(isset($mailsSend))
  507. {
  508. $returnValue = "".$mailsSend." Reminders send. ";
  509. if(isset($failedAddresses))
  510. $returnValue .= "\nCould not send to: ".$failedAddresses;
  511. return $returnValue;
  512. }
  513. break;
  514. default:
  515. break;
  516. }
  517. }
  518. /**
  519. * loginCheck for Lsrc, checks if the user with given password exists in LS Database and
  520. * sets the SESSION rights for this user
  521. * @param String $sUser
  522. * @param String $sPass
  523. * @return boolean
  524. */
  525. function checkUser($sUser, $sPass) // XXX
  526. {
  527. global $connect ;
  528. global $dbprefix ;
  529. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  530. include("lsrc.config.php");
  531. require(dirname(__FILE__)."/../classes/core/sha256.php");
  532. $query="SELECT uid, password, lang, superadmin FROM {$dbprefix}users WHERE users_name=".$connect->qstr(sanitize_user($sUser));
  533. // echo $query;
  534. $result = db_execute_assoc($query);
  535. $gv = $result->FetchRow();
  536. if($result->RecordCount() < 1)
  537. {
  538. return false;
  539. }
  540. else
  541. {
  542. if((SHA256::hashing($sPass)==$gv['password']))
  543. {
  544. $_SESSION['loginID']=$gv['uid'];
  545. $_SESSION['lang']=$gv['lang'];
  546. $squery = "SELECT create_survey, configurator, create_user, delete_user, superadmin, manage_template, manage_label FROM {$dbprefix}users WHERE uid={$gv['uid']}";
  547. $sresult = db_execute_assoc($squery); //Checked
  548. if ($sresult->RecordCount()>0)
  549. {
  550. $fields = $sresult->FetchRow();
  551. $_SESSION['USER_RIGHT_CREATE_SURVEY'] = $fields['create_survey'];
  552. $_SESSION['USER_RIGHT_CONFIGURATOR'] = $fields['configurator'];
  553. $_SESSION['USER_RIGHT_CREATE_USER'] = $fields['create_user'];
  554. $_SESSION['USER_RIGHT_DELETE_USER'] = $fields['delete_user'];
  555. $_SESSION['USER_RIGHT_SUPERADMIN'] = $fields['superadmin'];
  556. $_SESSION['USER_RIGHT_MANAGE_TEMPLATE'] = $fields['manage_template'];
  557. $_SESSION['USER_RIGHT_MANAGE_LABEL'] = $fields['manage_label'];
  558. }
  559. return true;
  560. }
  561. else
  562. {
  563. return false;
  564. }
  565. }
  566. }
  567. /**
  568. * Lsrc checks the existence of Surveys more than one time, so this makes sense to be DRY
  569. *
  570. * @param int $sid
  571. * @return boolean
  572. */
  573. function surveyExists($sid)//XXX
  574. {
  575. global $connect ;
  576. global $dbprefix ;
  577. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  578. include("lsrc.config.php");
  579. $query="SELECT * FROM {$dbprefix}surveys WHERE sid = ".$sid;
  580. // echo $query;
  581. $result = db_execute_assoc($query);
  582. if($result->RecordCount() < 1)
  583. {
  584. return false;
  585. }
  586. else
  587. {
  588. return true;
  589. }
  590. }
  591. /**
  592. * function to import surveys
  593. *
  594. * @param $iVid - desired survey id
  595. * @param $importFile - name of the file to import in core(survey) dir
  596. * @return boolean
  597. */
  598. function importSurvey($iVid, $importFile)
  599. {
  600. global $connect ;
  601. global $dbprefix ;
  602. global $clang;
  603. include("lsrc.config.php");
  604. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  605. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ");
  606. // HINT FOR IMPORTERS: go to Line 714 to manipulate the Survey, while it's imported
  607. $the_full_file_path = $coreDir.$importFile;
  608. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.",the_full_file_path ='$the_full_file_path' OK ");
  609. include("../import_functions.php");
  610. include("../admin_functions.php");
  611. if (!isset($copyfunction))
  612. {
  613. $sFullFilepath=$the_full_file_path;
  614. $aPathInfo = pathinfo($sFullFilepath);
  615. $sExtension = $aPathInfo['extension'];
  616. }
  617. if (isset($sExtension) && strtolower($sExtension)=='csv')
  618. {
  619. $aImportResults=CSVImportSurvey($sFullFilepath,$iVid);
  620. }
  621. elseif (isset($sExtension) && strtolower($sExtension)=='lss')
  622. {
  623. $aImportResults=XMLImportSurvey($sFullFilepath,NULL,NULL,$iVid);
  624. } elseif (isset($copyfunction))
  625. {
  626. $aImportResults=XMLImportSurvey('',$copysurveydata,$sNewSurveyName,$iVid);
  627. }
  628. //CANNOT BE USED BY LSRC RIGHT NOW
  629. // Translate INSERTANS codes if chosen
  630. // if (isset($aImportResults['fieldnames']) && $sTransLinks === true)
  631. // {
  632. // transInsertAns($aImportResults['newsid'],$aImportResults['oldsid'],$aImportResults['fieldnames']);
  633. // }
  634. return $aImportResults['newsid'];
  635. }
  636. /**
  637. * function to activate surveys based on new activate.php 5771 2008-10-13 02:28:40Z jcleeland $
  638. *
  639. * @param unknown_type $surveyid
  640. * @return boolean
  641. */
  642. function activateSurvey($surveyid)//XXX activateSurvey
  643. {
  644. global $dbprefix, $connect, $clang, $databasetype,$databasetabletype;
  645. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  646. include("lsrc.config.php");
  647. include('../admin_functions.php');
  648. include('../activate_functions.php');
  649. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  650. $returnOutput = activateSurvey($surveyid,$surveyid,'lsrc');
  651. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", $returnOutput ");
  652. return $returnOutput;
  653. } // end activateSurvey();
  654. /**
  655. * not used, a test, thought this could maybe enhance security, may be deleted
  656. *
  657. * @return Error 404 fake
  658. */
  659. function fake404()// XXX
  660. {
  661. return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  662. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  663. <html xmlns="http://www.w3.org/1999/xhtml" lang="de" xml:lang="de">
  664. <head>
  665. <title>Objekt nicht gefunden!</title>
  666. <link rev="made" href="" />
  667. <style type="text/css"><!--/*--><![CDATA[/*><!--*/
  668. body { color: #000000; background-color: #FFFFFF; }
  669. a:link { color: #0000CC; }
  670. p, address {margin-left: 3em;}
  671. span {font-size: smaller;}
  672. /*]]>*/--></style>
  673. </head>
  674. <body>
  675. <h1>Objekt nicht gefunden!</h1>
  676. <p>
  677. Der angeforderte URL konnte auf dem Server nicht gefunden werden.
  678. Sofern Sie den URL manuell eingegeben haben,
  679. &uuml;berpr&uuml;fen Sie bitte die Schreibweise und versuchen Sie es erneut.
  680. </p>
  681. <p>
  682. Sofern Sie dies f&uuml;r eine Fehlfunktion des Servers halten,
  683. informieren Sie bitte den
  684. <a href="mailto:webmaster@'.$_SERVER["SERVER_NAME"].'">Webmaster</a>
  685. hier&uuml;ber.
  686. </p>
  687. <h2>Error 404</h2>
  688. <address>
  689. <a href="/">'.$_SERVER["SERVER_NAME"].'</a>
  690. <span>'.date("m/d/Y H:i:s").'
  691. Apache/2.2.9 (Win32) DAV/2 mod_ssl/2.2.9 OpenSSL/0.9.8i mod_autoindex_color PHP/5.2.6 mod_jk/1.2.26</span>
  692. </address>
  693. </body>
  694. </html>
  695. ';
  696. }
  697. /**
  698. * importing a group into an existing survey
  699. *
  700. * @param int $iVid SurveyID
  701. * @param string $sMod Group that should be loaded into the Survey
  702. */
  703. function importGroup($surveyid, $sMod) //XXX
  704. {
  705. global $connect ;
  706. global $dbprefix ;
  707. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  708. include("lsrc.config.php");
  709. $newsid = $surveyid;
  710. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  711. $the_full_file_path = $modDir.$sMod.".csv";
  712. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK $the_full_file_path ");
  713. $handle = fopen($the_full_file_path, "r");
  714. while (!feof($handle))
  715. {
  716. $buffer = fgets($handle);
  717. $bigarray[] = $buffer;
  718. }
  719. fclose($handle);
  720. if (substr($bigarray[0], 0, 23) != "# LimeSurvey Group Dump" && substr($bigarray[0], 0, 24) != "# PHPSurveyor Group Dump")
  721. {
  722. //$importgroup .= "<strong><font color='red'>".("Error")."</font></strong>\n";
  723. //$importgroup .= ("This file is not a LimeSurvey group file. Import failed.")."\n";
  724. //$importgroup .= "<input type='submit' value='".("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\">\n";
  725. //$importgroup .= "</td></tr></table>\n";
  726. //unlink($the_full_file_path);
  727. return false;
  728. }
  729. for ($i=0; $i<9; $i++)
  730. {
  731. unset($bigarray[$i]);
  732. }
  733. $bigarray = array_values($bigarray);
  734. //GROUPS
  735. if (array_search("# QUESTIONS TABLE\n", $bigarray))
  736. {
  737. $stoppoint = array_search("# QUESTIONS TABLE\n", $bigarray);
  738. }
  739. elseif (array_search("# QUESTIONS TABLE\r\n", $bigarray))
  740. {
  741. $stoppoint = array_search("# QUESTIONS TABLE\r\n", $bigarray);
  742. }
  743. else
  744. {
  745. $stoppoint = count($bigarray)-1;
  746. }
  747. for ($i=0; $i<=$stoppoint+1; $i++)
  748. {
  749. if ($i<$stoppoint-2) {$grouparray[] = $bigarray[$i];}
  750. unset($bigarray[$i]);
  751. }
  752. $bigarray = array_values($bigarray);
  753. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  754. //QUESTIONS
  755. if (array_search("# ANSWERS TABLE\n", $bigarray))
  756. {
  757. $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
  758. }
  759. elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
  760. {
  761. $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
  762. }
  763. else
  764. {
  765. $stoppoint = count($bigarray)-1;
  766. }
  767. for ($i=0; $i<=$stoppoint+1; $i++)
  768. {
  769. if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];}
  770. unset($bigarray[$i]);
  771. }
  772. $bigarray = array_values($bigarray);
  773. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  774. //ANSWERS
  775. if (array_search("# CONDITIONS TABLE\n", $bigarray))
  776. {
  777. $stoppoint = array_search("# CONDITIONS TABLE\n", $bigarray);
  778. }
  779. elseif (array_search("# CONDITIONS TABLE\r\n", $bigarray))
  780. {
  781. $stoppoint = array_search("# CONDITIONS TABLE\r\n", $bigarray);
  782. }
  783. else
  784. {
  785. $stoppoint = count($bigarray)-1;
  786. }
  787. for ($i=0; $i<=$stoppoint+1; $i++)
  788. {
  789. if ($i<$stoppoint-2) {$answerarray[] = $bigarray[$i];}
  790. unset($bigarray[$i]);
  791. }
  792. $bigarray = array_values($bigarray);
  793. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  794. //CONDITIONS
  795. if (array_search("# LABELSETS TABLE\n", $bigarray))
  796. {
  797. $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
  798. }
  799. elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
  800. {
  801. $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
  802. }
  803. else
  804. {
  805. $stoppoint = count($bigarray);
  806. }
  807. for ($i=0; $i<=$stoppoint+1; $i++)
  808. {
  809. if ($i<$stoppoint-2) {$conditionsarray[] = $bigarray[$i];}
  810. unset($bigarray[$i]);
  811. }
  812. $bigarray = array_values($bigarray);
  813. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  814. //LABELSETS
  815. if (array_search("# LABELS TABLE\n", $bigarray))
  816. {
  817. $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
  818. }
  819. elseif (array_search("# LABELS TABLE\r\n", $bigarray))
  820. {
  821. $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
  822. }
  823. else
  824. {
  825. $stoppoint = count($bigarray)-1;
  826. }
  827. for ($i=0; $i<=$stoppoint+1; $i++)
  828. {
  829. if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
  830. unset($bigarray[$i]);
  831. }
  832. $bigarray = array_values($bigarray);
  833. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  834. //LABELS
  835. if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
  836. {
  837. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
  838. }
  839. elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
  840. {
  841. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
  842. }
  843. else
  844. {
  845. $stoppoint = count($bigarray)-1;
  846. }
  847. for ($i=0; $i<=$stoppoint+1; $i++)
  848. {
  849. if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
  850. unset($bigarray[$i]);
  851. }
  852. $bigarray = array_values($bigarray);
  853. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  854. //LAST LOT (now question_attributes)
  855. if (!isset($noconditions) || $noconditions != "Y")
  856. {
  857. // stoppoint is the last line number
  858. // this is an empty line after the QA CSV lines
  859. $stoppoint = count($bigarray)-1;
  860. for ($i=0; $i<=$stoppoint+1; $i++)
  861. {
  862. if ($i<=$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];}
  863. unset($bigarray[$i]);
  864. }
  865. }
  866. $bigarray = array_values($bigarray);
  867. $countgroups=0;
  868. if (isset($questionarray))
  869. {
  870. $questionfieldnames=convertCSVRowToArray($questionarray[0],',','"');
  871. unset($questionarray[0]);
  872. $countquestions = 0;
  873. }
  874. if (isset($answerarray))
  875. {
  876. $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"');
  877. unset($answerarray[0]);
  878. $countanswers = 0;
  879. }
  880. $countconditions = 0;
  881. $countlabelsets=0;
  882. $countlabels=0;
  883. $countquestion_attributes = 0;
  884. $countanswers = 0;
  885. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  886. // first check that imported group, questions and labels support the
  887. // current survey's baselang
  888. $langcode = GetBaseLanguageFromSurveyID($newsid);
  889. if (isset($grouparray))
  890. {
  891. $groupfieldnames = convertCSVRowToArray($grouparray[0],',','"');
  892. $langfieldnum = array_search("language", $groupfieldnames);
  893. $gidfieldnum = array_search("gid", $groupfieldnames);
  894. $groupssupportbaselang = bDoesImportarraySupportsLanguage($grouparray,Array($gidfieldnum),$langfieldnum,$langcode,true);
  895. if (!$groupssupportbaselang)
  896. {
  897. //$importgroup .= "<strong><font color='red'>".("Error")."</font></strong>\n";
  898. //$importgroup .= ("You can't import a group which doesn't support the current survey's base language.")."\n";
  899. //$importgroup .= "<input type='submit' value='".("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\">\n";
  900. //$importgroup .= "</td></tr></table>\n";
  901. //unlink($the_full_file_path);
  902. return "Group does not support Surveys Baselanguage ($langcode)";
  903. }
  904. }
  905. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  906. if (isset($questionarray))
  907. {
  908. $langfieldnum = array_search("language", $questionfieldnames);
  909. $qidfieldnum = array_search("qid", $questionfieldnames);
  910. $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,false);
  911. if (!$questionssupportbaselang)
  912. {
  913. //$importgroup .= "<strong><font color='red'>".("Error")."</font></strong>\n";
  914. //$importgroup .= ("You can't import a question which doesn't support the current survey's base language.")."\n";
  915. //$importgroup .= "<input type='submit' value='".("Main Admin Screen")."' onclick=\"window.open('$scriptname', '_top')\">\n";
  916. //$importgroup .= "</td></tr></table>\n";
  917. //unlink($the_full_file_path);
  918. return "Group does not support Surveys Baselanguage ($langcode)";
  919. }
  920. }
  921. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  922. if (isset($labelsetsarray))
  923. {
  924. $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"');
  925. $langfieldnum = array_search("languages", $labelsetfieldname);
  926. $lidfilednum = array_search("lid", $labelsetfieldname);
  927. $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true);
  928. if (!$labelsetssupportbaselang)
  929. {
  930. $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
  931. .("You can't import label sets which don't support the current survey's base language")."\n"
  932. ."</td></tr></table>\n";
  933. //unlink($the_full_file_path);
  934. return "Group does not support Surveys Baselanguage ($langcode)";
  935. }
  936. }
  937. $newlids = array(); // this array will have the "new lid" for the label sets, the key will be the "old lid"
  938. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  939. //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
  940. if (isset($labelsetsarray) && $labelsetsarray) {
  941. $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets
  942. $count=0;
  943. foreach ($labelsetsarray as $lsa) {
  944. $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"');
  945. $fieldcontents=convertCSVRowToArray($lsa,',','"');
  946. if ($count==0) {$count++; continue;}
  947. $countlabelsets++;
  948. $labelsetrowdata=array_combine($fieldorders,$fieldcontents);
  949. // Save old labelid
  950. $oldlid=$labelsetrowdata['lid'];
  951. // set the new language
  952. unset($labelsetrowdata['lid']);
  953. $newvalues=array_values($labelsetrowdata);
  954. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  955. $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  956. $lsiresult=$connect->Execute($lsainsert);
  957. // Get the new insert id for the labels inside this labelset
  958. $newlid=$connect->Insert_ID("{$dbprefix}labelsets",'lid');
  959. if ($labelsarray) {
  960. $count=0;
  961. foreach ($labelsarray as $la) {
  962. $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"');
  963. $lfieldcontents=convertCSVRowToArray($la,',','"');
  964. if ($count==0) {$count++; continue;}
  965. // Combine into one array with keys and values since its easier to handle
  966. $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
  967. $labellid=$labelrowdata['lid'];
  968. if ($labellid == $oldlid) {
  969. $labelrowdata['lid']=$newlid;
  970. // translate internal links
  971. $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
  972. $newvalues=array_values($labelrowdata);
  973. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  974. $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  975. $liresult=$connect->Execute($lainsert);
  976. $countlabels++;
  977. }
  978. }
  979. }
  980. //CHECK FOR DUPLICATE LABELSETS
  981. $thisset="";
  982. $query2 = "SELECT code, title, sortorder, language
  983. FROM {$dbprefix}labels
  984. WHERE lid=".$newlid."
  985. ORDER BY language, sortorder, code";
  986. $result2 = db_execute_num($query2) or $this->debugLsrc("Died querying labelset $lid$query2".$connect->ErrorMsg());
  987. while($row2=$result2->FetchRow())
  988. {
  989. $thisset .= implode('.', $row2);
  990. } // while
  991. $newcs=dechex(crc32($thisset)*1);
  992. unset($lsmatch);
  993. if (isset($csarray))
  994. {
  995. foreach($csarray as $key=>$val)
  996. {
  997. if ($val == $newcs)
  998. {
  999. $lsmatch=$key;
  1000. }
  1001. }
  1002. }
  1003. if (isset($lsmatch))
  1004. {
  1005. //There is a matching labelset. So, we will delete this one and refer
  1006. //to the matched one.
  1007. $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
  1008. $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labels$query".$connect->ErrorMsg());
  1009. $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
  1010. $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset$query".$connect->ErrorMsg());
  1011. $newlid=$lsmatch;
  1012. }
  1013. else
  1014. {
  1015. //There isn't a matching labelset, add this checksum to the $csarray array
  1016. $csarray[$newlid]=$newcs;
  1017. }
  1018. //END CHECK FOR DUPLICATES
  1019. $labelreplacements[]=array($oldlid, $newlid);
  1020. $newlids[$oldlid] = $newlid;
  1021. }
  1022. }
  1023. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1024. //these arrays will aloud to insert correctly groups an questions multi languague survey imports correctly, and will eliminate the need to "searh" the imported data
  1025. //$newgids = array(); // this array will have the "new gid" for the groups, the kwy will be the "old gid" <-- not needed when importing groups
  1026. $newqids = array(); // this array will have the "new qid" for the questions, the kwy will be the "old qid"
  1027. // DO GROUPS, QUESTIONS FOR GROUPS, THEN ANSWERS FOR QUESTIONS IN A __NOT__ NESTED FORMAT!
  1028. if (isset($grouparray) && $grouparray)
  1029. {
  1030. $surveylanguages=GetAdditionalLanguagesFromSurveyID($surveyid);
  1031. $surveylanguages[]=GetBaseLanguageFromSurveyID($surveyid);
  1032. // do GROUPS
  1033. $gafieldorders=convertCSVRowToArray($grouparray[0],',','"');
  1034. unset($grouparray[0]);
  1035. $newgid = 0;
  1036. $group_order = 0; // just to initialize this variable
  1037. foreach ($grouparray as $ga)
  1038. {
  1039. //GET ORDER OF FIELDS
  1040. $gacfieldcontents=convertCSVRowToArray($ga,',','"');
  1041. $grouprowdata=array_combine($gafieldorders,$gacfieldcontents);
  1042. // Skip not supported languages
  1043. if (!in_array($grouprowdata['language'],$surveylanguages))
  1044. {
  1045. $skippedlanguages[]=$grouprowdata['language']; // this is for the message in the end.
  1046. continue;
  1047. }
  1048. // replace the sid
  1049. $oldsid=$grouprowdata['sid'];
  1050. $grouprowdata['sid']=$newsid;
  1051. // replace the gid or remove it if needed (it also will calculate the group order if is a new group)
  1052. $oldgid=$grouprowdata['gid'];
  1053. if ($newgid == 0)
  1054. {
  1055. unset($grouprowdata['gid']);
  1056. // find the maximum group order and use this grouporder+1 to assign it to the new group
  1057. $qmaxgo = "select max(group_order) as maxgo from ".db_table_name('groups')." where sid=$newsid";
  1058. $gres = db_execute_assoc($qmaxgo) or $this->debugLsrc (("Error")." Failed to find out maximum group order value\n$qmaxqo\n".$connect->ErrorMsg());
  1059. $grow=$gres->FetchRow();
  1060. $group_order = $grow['maxgo']+1;
  1061. }
  1062. else
  1063. $grouprowdata['gid'] = $newgid;
  1064. $grouprowdata["group_order"]= $group_order;
  1065. // Everything set - now insert it
  1066. $grouprowdata=array_map('convertCsvreturn2return', $grouprowdata);
  1067. // translate internal links
  1068. $grouprowdata['group_name']=translink('survey', $oldsid, $newsid, $grouprowdata['group_name']);
  1069. $grouprowdata['description']=translink('survey', $oldsid, $newsid, $grouprowdata['description']);
  1070. $newvalues=array_values($grouprowdata);
  1071. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1072. $ginsert = "insert INTO {$dbprefix}groups (".implode(',',array_keys($grouprowdata)).") VALUES (".implode(',',$newvalues).")";
  1073. $gres = $connect->Execute($ginsert) or $this->debugLsrc("Error: ".": Failed to insert group\n$ginsert\n".$connect->ErrorMsg());
  1074. //GET NEW GID .... if is not done before and we count a group if a new gid is required
  1075. if ($newgid == 0)
  1076. {
  1077. $newgid = $connect->Insert_ID("{$dbprefix}groups",'gid');
  1078. $countgroups++;
  1079. }
  1080. }
  1081. // GROUPS is DONE
  1082. // do QUESTIONS
  1083. if (isset($questionarray) && $questionarray)
  1084. {
  1085. foreach ($questionarray as $qa)
  1086. {
  1087. $qacfieldcontents=convertCSVRowToArray($qa,',','"');
  1088. $questionrowdata=array_combine($questionfieldnames,$qacfieldcontents);
  1089. // Skip not supported languages
  1090. if (!in_array($questionrowdata['language'],$surveylanguages))
  1091. continue;
  1092. // replace the sid
  1093. $questionrowdata["sid"] = $newsid;
  1094. // replace the gid (if the gid is not in the oldgid it means there is a problem with the exported record, so skip it)
  1095. if ($questionrowdata['gid'] == $oldgid)
  1096. $questionrowdata['gid'] = $newgid;
  1097. else
  1098. continue; // a problem with this question record -> don't consider
  1099. // replace the qid or remove it if needed
  1100. $oldqid = $questionrowdata['qid'];
  1101. if (isset($newqids[$oldqid]))
  1102. $questionrowdata['qid'] = $newqids[$oldqid];
  1103. else
  1104. unset($questionrowdata['qid']);
  1105. // replace the lid for the new one (if there is no new lid in the $newlids array it mean that was not imported -> error, skip this record)
  1106. if (in_array($questionrowdata["type"], array("F","W","Z","H", "1", ":", ";"))) // only fot the questions that uses a label set.
  1107. if (isset($newlids[$questionrowdata["lid"]]))
  1108. {
  1109. $questionrowdata["lid"] = $newlids[$questionrowdata["lid"]];
  1110. if(isset($newlids[$questionrowdata["lid1"]]))
  1111. {
  1112. $questionrowdata["lid1"] = $newlids[$questionrowdata["lid1"]];
  1113. }
  1114. }
  1115. else
  1116. {
  1117. continue; // a problem with this question record -> don't consider
  1118. }
  1119. // $other = $questionrowdata["other"]; //Get 'other' field value
  1120. // $oldlid = $questionrowdata['lid'];
  1121. // Everything set - now insert it
  1122. $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
  1123. // translate internal links ///XXX rakete may change question data here
  1124. // $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
  1125. // $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
  1126. // $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);
  1127. $newvalues=array_values($questionrowdata);
  1128. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1129. $qinsert = "insert INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")";
  1130. $qres = $connect->Execute($qinsert) or $this->debugLsrc ("Error: "."Failed to insert question\n$qinsert\n".$connect->ErrorMsg());
  1131. //GET NEW QID .... if is not done before and we count a question if a new qid is required
  1132. if (!isset($newqids[$oldqid]))
  1133. {
  1134. $newqids[$oldqid] = $connect->Insert_ID("{$dbprefix}questions",'qid');
  1135. $myQid=$newqids[$oldqid];
  1136. $countquestions++;
  1137. }
  1138. else
  1139. {
  1140. $myQid=$newqids[$oldqid];
  1141. }
  1142. }
  1143. }
  1144. // QESTIONS is DONE
  1145. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1146. // do ANSWERS
  1147. if (isset($answerarray) && $answerarray)
  1148. {
  1149. foreach ($answerarray as $aa)
  1150. {
  1151. $aacfieldcontents=convertCSVRowToArray($aa,',','"');
  1152. $answerrowdata=array_combine($answerfieldnames,$aacfieldcontents);
  1153. // Skip not supported languages
  1154. if (!in_array($answerrowdata['language'],$surveylanguages))
  1155. continue;
  1156. // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this answer is orphan -> error, skip this record)
  1157. if (isset($newqids[$answerrowdata["qid"]]))
  1158. $answerrowdata["qid"] = $newqids[$answerrowdata["qid"]];
  1159. else
  1160. continue; // a problem with this answer record -> don't consider
  1161. // Everything set - now insert it
  1162. $answerrowdata = array_map('convertCsvreturn2return', $answerrowdata);
  1163. // translate internal links
  1164. $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
  1165. $newvalues=array_values($answerrowdata);
  1166. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1167. $ainsert = "insert INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")";
  1168. $ares = $connect->Execute($ainsert) or $this->debugLsrc ("Error: "."Failed to insert answer\n$ainsert\n".$connect->ErrorMsg());
  1169. $countanswers++;
  1170. }
  1171. }
  1172. // ANSWERS is DONE
  1173. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1174. // Fix question group sortorder
  1175. fixSortOrderGroups($surveyid);
  1176. $baselang = GetBaseLanguageFromSurveyID($surveyid);
  1177. $cdresult = db_execute_assoc("SELECT gid FROM ".db_table_name('groups')." WHERE sid='{$surveyid}' AND language='{$baselang}' ORDER BY group_order, group_name");
  1178. $position=0;
  1179. while ($cdrow=$cdresult->FetchRow())
  1180. {
  1181. $cd2query="UPDATE ".db_table_name('groups')." SET group_order='{$position}' WHERE gid='{$cdrow['gid']}' ";
  1182. $cd2result = $connect->Execute($cd2query) or $this->debugLsrc ("Couldn't update group_order$cd2query".$connect->ErrorMsg()); //Checked
  1183. $position++;
  1184. }
  1185. //... and for the questions inside the groups
  1186. // get all group ids and fix questions inside each group
  1187. $gquery = "SELECT gid FROM {$dbprefix}groups where sid=$newsid group by gid ORDER BY gid"; //Get last question added (finds new qid)
  1188. $gres = db_execute_assoc($gquery);
  1189. while ($grow = $gres->FetchRow())
  1190. {
  1191. //fixsortorderQuestions(0,$grow['gid']);
  1192. $qid=sanitize_int(0);
  1193. $gid=sanitize_int($grow['gid']);
  1194. $baselang = GetBaseLanguageFromSurveyID($surveyid);
  1195. if ($gid == 0)
  1196. {
  1197. $result = db_execute_assoc("SELECT gid FROM ".db_table_name('questions')." WHERE qid='{$qid}' and language='{$baselang}'"); //Checked
  1198. $row=$result->FetchRow();
  1199. $gid=$row['gid'];
  1200. }
  1201. $cdresult = db_execute_assoc("SELECT qid FROM ".db_table_name('questions')." WHERE gid='{$gid}' and language='{$baselang}' ORDER BY question_order, title ASC"); //Checked
  1202. $position=0;
  1203. while ($cdrow=$cdresult->FetchRow())
  1204. {
  1205. $cd2query="UPDATE ".db_table_name('questions')." SET question_order='{$position}' WHERE qid='{$cdrow['qid']}' ";
  1206. $cd2result = $connect->Execute($cd2query) or $this->debugLsrc ("Couldn't update question_order$cd2query".$connect->ErrorMsg()); //Checked
  1207. $position++;
  1208. }
  1209. }
  1210. }
  1211. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1212. // do ATTRIBUTES
  1213. if (isset($question_attributesarray) && $question_attributesarray)
  1214. {
  1215. $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"');
  1216. unset($question_attributesarray[0]);
  1217. foreach ($question_attributesarray as $qar) {
  1218. $fieldcontents=convertCSVRowToArray($qar,',','"');
  1219. $qarowdata=array_combine($fieldorders,$fieldcontents);
  1220. // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this attribute is orphan -> error, skip this record)
  1221. if (isset($newqids[$qarowdata["qid"]]))
  1222. $qarowdata["qid"] = $newqids[$qarowdata["qid"]];
  1223. else
  1224. continue; // a problem with this answer record -> don't consider
  1225. unset($qarowdata["qaid"]);
  1226. // Everything set - now insert it
  1227. $newvalues=array_values($qarowdata);
  1228. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1229. $qainsert = "insert INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")";
  1230. $result=$connect->Execute($qainsert) or $this->debugLsrc ("Couldn't insert question_attribute$qainsert".$connect->ErrorMsg());
  1231. $countquestion_attributes++;
  1232. }
  1233. }
  1234. // ATTRIBUTES is DONE
  1235. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1236. // do CONDITIONS
  1237. if (isset($conditionsarray) && $conditionsarray)
  1238. {
  1239. $fieldorders=convertCSVRowToArray($conditionsarray[0],',','"');
  1240. unset($conditionsarray[0]);
  1241. foreach ($conditionsarray as $car) {
  1242. $fieldcontents=convertCSVRowToArray($car,',','"');
  1243. $conditionrowdata=array_combine($fieldorders,$fieldcontents);
  1244. $oldqid = $conditionrowdata["qid"];
  1245. $oldcqid = $conditionrowdata["cqid"];
  1246. // replace the qid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record)
  1247. if (isset($newqids[$oldqid]))
  1248. $conditionrowdata["qid"] = $newqids[$oldqid];
  1249. else
  1250. continue; // a problem with this answer record -> don't consider
  1251. // replace the cqid for the new one (if there is no new qid in the $newqids array it mean that this condition is orphan -> error, skip this record)
  1252. if (isset($newqids[$oldcqid]))
  1253. $conditionrowdata["cqid"] = $newqids[$oldcqid];
  1254. else
  1255. continue; // a problem with this answer record -> don't consider
  1256. list($oldcsid, $oldcgid, $oldqidanscode) = explode("X",$conditionrowdata["cfieldname"],3);
  1257. if ($oldcgid != $oldgid) // this means that the condition is in another group (so it should not have to be been exported -> skip it
  1258. continue;
  1259. unset($conditionrowdata["cid"]);
  1260. // recreate the cfieldname with the new IDs
  1261. $newcfieldname = $newsid . "X" . $newgid . "X" . $conditionrowdata["cqid"] .substr($oldqidanscode,strlen($oldqid));
  1262. $conditionrowdata["cfieldname"] = $newcfieldname;
  1263. if (!isset($conditionrowdata["method"]) || trim($conditionrowdata["method"])=='')
  1264. {
  1265. $conditionrowdata["method"]='==';
  1266. }
  1267. $newvalues=array_values($conditionrowdata);
  1268. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1269. $conditioninsert = "insert INTO {$dbprefix}conditions (".implode(',',array_keys($conditionrowdata)).") VALUES (".implode(',',$newvalues).")";
  1270. $result=$connect->Execute($conditioninsert) or $this->debugLsrc ("Couldn't insert condition$conditioninsert".$connect->ErrorMsg());
  1271. $countconditions++;
  1272. }
  1273. }
  1274. $this->debugLsrc("wir sind in - ".__FUNCTION__." Line ".__LINE__.", FERTIG ");
  1275. // CONDITIONS is DONE
  1276. return array('gid'=>$newgid,'qid'=>$myQid);
  1277. //return $newgid;
  1278. }
  1279. /**
  1280. *
  1281. * Enter description here...
  1282. * @param $surveyid
  1283. * @param $sMod
  1284. * @param $newGroup
  1285. * @return unknown_type
  1286. */
  1287. function importQuestion($surveyid, $sMod, $newGroup=false) //XXX
  1288. {
  1289. global $connect ;
  1290. global $dbprefix ;
  1291. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  1292. include("lsrc.config.php");
  1293. $newsid = $surveyid;
  1294. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", START OK $dbprefix ");
  1295. //$getGidSql = "SELECT gid FROM {$dbprefix} ";
  1296. $getGidSql = "SELECT gid
  1297. FROM {$dbprefix}groups
  1298. WHERE sid=".$surveyid." AND language='".GetBaseLanguageFromSurveyID($surveyid)."'
  1299. ORDER BY gid desc ";
  1300. $getGidRs = db_execute_num($getGidSql);
  1301. $gidRow=$getGidRs->FetchRow();
  1302. $gid = $gidRow[0];
  1303. if($gid=='')#
  1304. {
  1305. $this->debugLsrc("No Group for importing the question, available!");
  1306. return "No Group for importing the question, available! Import failed.";
  1307. }
  1308. if($newGroup===true)
  1309. ++$gid;
  1310. $the_full_file_path = $queDir.$sMod.".csv";
  1311. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK $the_full_file_path ");
  1312. $handle = fopen($the_full_file_path, "r");
  1313. while (!feof($handle))
  1314. {
  1315. $buffer = fgets($handle, 10240); //To allow for very long survey welcomes (up to 10k)
  1316. $bigarray[] = $buffer;
  1317. }
  1318. fclose($handle);
  1319. // Now we try to determine the dataformat of the survey file.
  1320. if ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 29) == "# http://www.phpsurveyor.org/"))
  1321. {
  1322. $importversion = 100; // version 1.0 file
  1323. }
  1324. elseif
  1325. ((substr($bigarray[1], 0, 24) == "# SURVEYOR QUESTION DUMP")&& (substr($bigarray[4], 0, 37) == "# http://phpsurveyor.sourceforge.net/"))
  1326. {
  1327. $importversion = 99; // Version 0.99 file or older - carries a different URL
  1328. }
  1329. elseif
  1330. (substr($bigarray[0], 0, 26) == "# LimeSurvey Question Dump" || substr($bigarray[0], 0, 27) == "# PHPSurveyor Question Dump")
  1331. { // Wow.. this seems to be a >1.0 version file - these files carry the version information to read in line two
  1332. $importversion=substr($bigarray[1], 12, 3);
  1333. }
  1334. else // unknown file - show error message
  1335. {
  1336. // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n";
  1337. // $importquestion .= ("This file is not a LimeSurvey question file. Import failed.")."\n";
  1338. // $importquestion .= "</font></td></tr></table>\n";
  1339. // $importquestion .= "</body>\n</html>\n";
  1340. // unlink($the_full_file_path);
  1341. return "This is not a Limesurvey question file. Import failed";
  1342. }
  1343. // if ($importversion != $dbversionnumber)
  1344. // {
  1345. //// $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n";
  1346. //// $importquestion .= ("Sorry, importing questions is limited to the same version. Import failed.")."\n";
  1347. //// $importquestion .= "</font></td></tr></table>\n";
  1348. //// $importquestion .= "</body>\n</html>\n";
  1349. //// unlink($the_full_file_path);
  1350. // return;
  1351. // }
  1352. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1353. for ($i=0; $i<9; $i++) //skipping the first lines that are not needed
  1354. {
  1355. unset($bigarray[$i]);
  1356. }
  1357. $bigarray = array_values($bigarray);
  1358. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1359. //QUESTIONS
  1360. if (array_search("# ANSWERS TABLE\n", $bigarray))
  1361. {
  1362. $stoppoint = array_search("# ANSWERS TABLE\n", $bigarray);
  1363. }
  1364. elseif (array_search("# ANSWERS TABLE\r\n", $bigarray))
  1365. {
  1366. $stoppoint = array_search("# ANSWERS TABLE\r\n", $bigarray);
  1367. }
  1368. else
  1369. {
  1370. $stoppoint = count($bigarray)-1;
  1371. }
  1372. for ($i=0; $i<=$stoppoint+1; $i++)
  1373. {
  1374. if ($i<$stoppoint-2) {$questionarray[] = $bigarray[$i];}
  1375. unset($bigarray[$i]);
  1376. }
  1377. $bigarray = array_values($bigarray);
  1378. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1379. //ANSWERS
  1380. if (array_search("# LABELSETS TABLE\n", $bigarray))
  1381. {
  1382. $stoppoint = array_search("# LABELSETS TABLE\n", $bigarray);
  1383. }
  1384. elseif (array_search("# LABELSETS TABLE\r\n", $bigarray))
  1385. {
  1386. $stoppoint = array_search("# LABELSETS TABLE\r\n", $bigarray);
  1387. }
  1388. else
  1389. {
  1390. $stoppoint = count($bigarray)-1;
  1391. }
  1392. for ($i=0; $i<=$stoppoint+1; $i++)
  1393. {
  1394. if ($i<$stoppoint-2) {$answerarray[] = str_replace("`default`", "`default_value`", $bigarray[$i]);}
  1395. unset($bigarray[$i]);
  1396. }
  1397. $bigarray = array_values($bigarray);
  1398. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1399. //LABELSETS
  1400. if (array_search("# LABELS TABLE\n", $bigarray))
  1401. {
  1402. $stoppoint = array_search("# LABELS TABLE\n", $bigarray);
  1403. }
  1404. elseif (array_search("# LABELS TABLE\r\n", $bigarray))
  1405. {
  1406. $stoppoint = array_search("# LABELS TABLE\r\n", $bigarray);
  1407. }
  1408. else
  1409. {
  1410. $stoppoint = count($bigarray)-1;
  1411. }
  1412. for ($i=0; $i<=$stoppoint+1; $i++)
  1413. {
  1414. if ($i<$stoppoint-2) {$labelsetsarray[] = $bigarray[$i];}
  1415. unset($bigarray[$i]);
  1416. }
  1417. $bigarray = array_values($bigarray);
  1418. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1419. //LABELS
  1420. if (array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray))
  1421. {
  1422. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\n", $bigarray);
  1423. }
  1424. elseif (array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray))
  1425. {
  1426. $stoppoint = array_search("# QUESTION_ATTRIBUTES TABLE\r\n", $bigarray);
  1427. }
  1428. else
  1429. {
  1430. $stoppoint = count($bigarray)-1;
  1431. }
  1432. for ($i=0; $i<=$stoppoint+1; $i++)
  1433. {
  1434. if ($i<$stoppoint-2) {$labelsarray[] = $bigarray[$i];}
  1435. unset($bigarray[$i]);
  1436. }
  1437. $bigarray = array_values($bigarray);
  1438. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1439. //Question_attributes
  1440. if (!isset($noconditions) || $noconditions != "Y")
  1441. {
  1442. $stoppoint = count($bigarray);
  1443. for ($i=0; $i<=$stoppoint+1; $i++)
  1444. {
  1445. if ($i<$stoppoint-1) {$question_attributesarray[] = $bigarray[$i];}
  1446. unset($bigarray[$i]);
  1447. }
  1448. }
  1449. $bigarray = array_values($bigarray);
  1450. if (isset($questionarray)) {$countquestions = count($questionarray)-1;} else {$countquestions=0;}
  1451. if (isset($answerarray))
  1452. {
  1453. $answerfieldnames=convertCSVRowToArray($answerarray[0],',','"');
  1454. unset($answerarray[0]);
  1455. $countanswers = count($answerarray);
  1456. }
  1457. else {$countanswers=0;}
  1458. if (isset($labelsetsarray)) {$countlabelsets = count($labelsetsarray)-1;} else {$countlabelsets=0;}
  1459. if (isset($labelsarray)) {$countlabels = count($labelsarray)-1;} else {$countlabels=0;}
  1460. if (isset($question_attributesarray)) {$countquestion_attributes = count($question_attributesarray)-1;} else {$countquestion_attributes=0;}
  1461. $languagesSupported = array(); // this array will keep all the languages supported for the survey
  1462. // Let's check that imported objects support at least the survey's baselang
  1463. $langcode = GetBaseLanguageFromSurveyID($surveyid);
  1464. $languagesSupported[$langcode] = 1; // adds the base language to the list of supported languages
  1465. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1466. if ($countquestions > 0)
  1467. {
  1468. $questionfieldnames = convertCSVRowToArray($questionarray[0],',','"');
  1469. $langfieldnum = array_search("language", $questionfieldnames);
  1470. $qidfieldnum = array_search("qid", $questionfieldnames);
  1471. $questionssupportbaselang = bDoesImportarraySupportsLanguage($questionarray,Array($qidfieldnum), $langfieldnum,$langcode,true);
  1472. if (!$questionssupportbaselang)
  1473. {
  1474. // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
  1475. // .("You can't import a question which doesn't support the current survey's base language")."\n"
  1476. // ."</td></tr></table>\n";
  1477. // unlink($the_full_file_path);
  1478. return "You can't import a question which doesn't support the current survey's base language";
  1479. }
  1480. }
  1481. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1482. foreach (GetAdditionalLanguagesFromSurveyID($surveyid) as $language)
  1483. {
  1484. $languagesSupported[$language] = 1;
  1485. }
  1486. // Let's assume that if the questions do support tye baselang
  1487. // Then the answers do support it as well.
  1488. // ==> So the following section is commented for now
  1489. //if ($countanswers > 0)
  1490. //{
  1491. // $langfieldnum = array_search("language", $answerfieldnames);
  1492. // $answercodefilednum1 = array_search("qid", $answerfieldnames);
  1493. // $answercodefilednum2 = array_search("code", $answerfieldnames);
  1494. // $answercodekeysarr = Array($answercodefilednum1,$answercodefilednum2);
  1495. // $answerssupportbaselang = bDoesImportarraySupportsLanguage($answerarray,$answercodekeysarr,$langfieldnum,$langcode);
  1496. // if (!$answerssupportbaselang)
  1497. // {
  1498. // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
  1499. // .("You can't import answers which don't support current survey's base language")."\n"
  1500. // ."</td></tr></table>\n";
  1501. // return;
  1502. // }
  1503. //
  1504. //}
  1505. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1506. if ($countlabelsets > 0)
  1507. {
  1508. $labelsetfieldname = convertCSVRowToArray($labelsetsarray[0],',','"');
  1509. $langfieldnum = array_search("languages", $labelsetfieldname);
  1510. $lidfilednum = array_search("lid", $labelsetfieldname);
  1511. $labelsetssupportbaselang = bDoesImportarraySupportsLanguage($labelsetsarray,Array($lidfilednum),$langfieldnum,$langcode,true);
  1512. if (!$labelsetssupportbaselang)
  1513. {
  1514. // $importquestion .= "<strong><font color='red'>".("Error")."</font></strong>\n"
  1515. // .("You can't import label sets which don't support the current survey's base language")."\n"
  1516. // ."</td></tr></table>\n";
  1517. // unlink($the_full_file_path);
  1518. return "You can't import label sets which don't support the current survey's base language";
  1519. }
  1520. }
  1521. // I assume that if a labelset supports the survey's baselang,
  1522. // then it's labels do support it as well
  1523. // GET SURVEY AND GROUP DETAILS
  1524. //$surveyid=$postsid;
  1525. //$gid=$postgid;
  1526. $newsid=$surveyid;
  1527. $newgid=$gid;
  1528. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1529. //DO ANY LABELSETS FIRST, SO WE CAN KNOW WHAT THEIR NEW LID IS FOR THE QUESTIONS
  1530. if (isset($labelsetsarray) && $labelsetsarray) {
  1531. $csarray=buildLabelSetCheckSumArray(); // build checksums over all existing labelsets
  1532. $count=0;
  1533. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1534. foreach ($labelsetsarray as $lsa) {
  1535. $fieldorders =convertCSVRowToArray($labelsetsarray[0],',','"');
  1536. $fieldcontents=convertCSVRowToArray($lsa,',','"');
  1537. if ($count==0) {$count++; continue;}
  1538. $labelsetrowdata=array_combine($fieldorders,$fieldcontents);
  1539. // Save old labelid
  1540. $oldlid=$labelsetrowdata['lid'];
  1541. // set the new language
  1542. unset($labelsetrowdata['lid']);
  1543. $newvalues=array_values($labelsetrowdata);
  1544. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1545. $lsainsert = "INSERT INTO {$dbprefix}labelsets (".implode(',',array_keys($labelsetrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  1546. $lsiresult=$connect->Execute($lsainsert);
  1547. // Get the new insert id for the labels inside this labelset
  1548. $newlid=$connect->Insert_ID("{$dbprefix}labelsets","lid");
  1549. if ($labelsarray) {
  1550. $count=0;
  1551. foreach ($labelsarray as $la) {
  1552. $lfieldorders =convertCSVRowToArray($labelsarray[0],',','"');
  1553. $lfieldcontents=convertCSVRowToArray($la,',','"');
  1554. if ($count==0) {$count++; continue;}
  1555. // Combine into one array with keys and values since its easier to handle
  1556. $labelrowdata=array_combine($lfieldorders,$lfieldcontents);
  1557. $labellid=$labelrowdata['lid'];
  1558. if ($labellid == $oldlid) {
  1559. $labelrowdata['lid']=$newlid;
  1560. // translate internal links
  1561. $labelrowdata['title']=translink('label', $oldlid, $newlid, $labelrowdata['title']);
  1562. $newvalues=array_values($labelrowdata);
  1563. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1564. $lainsert = "INSERT INTO {$dbprefix}labels (".implode(',',array_keys($labelrowdata)).") VALUES (".implode(',',$newvalues).")"; //handle db prefix
  1565. $liresult=$connect->Execute($lainsert);
  1566. }
  1567. }
  1568. }
  1569. //CHECK FOR DUPLICATE LABELSETS
  1570. $thisset="";
  1571. $query2 = "SELECT code, title, sortorder, language
  1572. FROM {$dbprefix}labels
  1573. WHERE lid=".$newlid."
  1574. ORDER BY language, sortorder, code";
  1575. $result2 = db_execute_num($query2) or $this->debugLsrc("Died querying labelset $lid$query2".$connect->ErrorMsg());
  1576. while($row2=$result2->FetchRow())
  1577. {
  1578. $thisset .= implode('.', $row2);
  1579. } // while
  1580. $newcs=dechex(crc32($thisset)*1);
  1581. unset($lsmatch);
  1582. if (isset($csarray))
  1583. {
  1584. foreach($csarray as $key=>$val)
  1585. {
  1586. if ($val == $newcs)
  1587. {
  1588. $lsmatch=$key;
  1589. }
  1590. }
  1591. }
  1592. if (isset($lsmatch))
  1593. {
  1594. //There is a matching labelset. So, we will delete this one and refer
  1595. //to the matched one.
  1596. $query = "DELETE FROM {$dbprefix}labels WHERE lid=$newlid";
  1597. $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labels$query".$connect->ErrorMsg());
  1598. $query = "DELETE FROM {$dbprefix}labelsets WHERE lid=$newlid";
  1599. $result=$connect->Execute($query) or $this->debugLsrc("Couldn't delete labelset$query".$connect->ErrorMsg());
  1600. $newlid=$lsmatch;
  1601. }
  1602. else
  1603. {
  1604. //There isn't a matching labelset, add this checksum to the $csarray array
  1605. $csarray[$newlid]=$newcs;
  1606. }
  1607. //END CHECK FOR DUPLICATES
  1608. $labelreplacements[]=array($oldlid, $newlid);
  1609. }
  1610. }
  1611. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1612. // QUESTIONS, THEN ANSWERS FOR QUESTIONS IN A NESTED FORMAT!
  1613. if (isset($questionarray) && $questionarray) {
  1614. $qafieldorders=convertCSVRowToArray($questionarray[0],',','"');
  1615. unset($questionarray[0]);
  1616. //Assuming we will only import one question at a time we will now find out the maximum question order in this group
  1617. //and save it for later
  1618. $qmaxqo = "SELECT MAX(question_order) AS maxqo FROM ".db_table_name('questions')." WHERE sid=$newsid AND gid=$newgid";
  1619. $qres = db_execute_assoc($qmaxqo) or $this->debugLsrc ("Error: ".": Failed to find out maximum question order value\n$qmaxqo\n".$connect->ErrorMsg());
  1620. $qrow=$qres->FetchRow();
  1621. $newquestionorder=$qrow['maxqo']+1;
  1622. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1623. foreach ($questionarray as $qa) {
  1624. $qacfieldcontents=convertCSVRowToArray($qa,',','"');
  1625. $newfieldcontents=$qacfieldcontents;
  1626. $questionrowdata=array_combine($qafieldorders,$qacfieldcontents);
  1627. if (isset($languagesSupported[$questionrowdata["language"]]))
  1628. {
  1629. $oldqid = $questionrowdata['qid'];
  1630. $oldsid = $questionrowdata['sid'];
  1631. $oldgid = $questionrowdata['gid'];
  1632. // Remove qid field if there is no newqid; and set it to newqid if it's set
  1633. if (!isset($newqid))
  1634. unset($questionrowdata['qid']);
  1635. else
  1636. $questionrowdata['qid'] = $newqid;
  1637. $questionrowdata["sid"] = $newsid;
  1638. $questionrowdata["gid"] = $newgid;
  1639. $questionrowdata["question_order"] = $newquestionorder;
  1640. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1641. // Now we will fix up the label id
  1642. $type = $questionrowdata["type"]; //Get the type
  1643. if ($type == "F" || $type == "H" || $type == "1" || $type == ":" || $type == ";" )
  1644. {//IF this is a flexible label array, update the lid entry
  1645. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1646. if (isset($labelreplacements)) {
  1647. foreach ($labelreplacements as $lrp) {
  1648. if ($lrp[0] == $questionrowdata["lid"]) {
  1649. $questionrowdata["lid"]=$lrp[1];
  1650. }
  1651. if ($lrp[0] == $questionrowdata["lid1"]) {
  1652. $questionrowdata["lid1"]=$lrp[1];
  1653. }
  1654. }
  1655. }
  1656. }
  1657. $other = $questionrowdata["other"]; //Get 'other' field value
  1658. $oldlid = $questionrowdata["lid"];
  1659. $questionrowdata=array_map('convertCsvreturn2return', $questionrowdata);
  1660. // translate internal links
  1661. $questionrowdata['title']=translink('survey', $oldsid, $newsid, $questionrowdata['title']);
  1662. $questionrowdata['question']=translink('survey', $oldsid, $newsid, $questionrowdata['question']);
  1663. $questionrowdata['help']=translink('survey', $oldsid, $newsid, $questionrowdata['help']);
  1664. $newvalues=array_values($questionrowdata);
  1665. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1666. $qinsert = "INSERT INTO {$dbprefix}questions (".implode(',',array_keys($questionrowdata)).") VALUES (".implode(',',$newvalues).")";
  1667. $qres = $connect->Execute($qinsert) or $this->debugLsrc ("Error: ".": Failed to insert question\n$qinsert\n".$connect->ErrorMsg());
  1668. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1669. // set the newqid only if is not set
  1670. if (!isset($newqid))
  1671. $newqid=$connect->Insert_ID("{$dbprefix}questions","qid");
  1672. }
  1673. }
  1674. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1675. //NOW DO ANSWERS FOR THIS QID - Is called just once and only if there was a question
  1676. if (isset($answerarray) && $answerarray) {
  1677. foreach ($answerarray as $aa) {
  1678. $answerfieldcontents=convertCSVRowToArray($aa,',','"');
  1679. $answerrowdata=array_combine($answerfieldnames,$answerfieldcontents);
  1680. if ($answerrowdata===false)
  1681. {
  1682. $importquestion.=''.("Faulty line in import - fields and data don't match").":".implode(',',$answerfieldcontents);
  1683. }
  1684. if (isset($languagesSupported[$answerrowdata["language"]]))
  1685. {
  1686. $code=$answerrowdata["code"];
  1687. $thisqid=$answerrowdata["qid"];
  1688. $answerrowdata["qid"]=$newqid;
  1689. // translate internal links
  1690. $answerrowdata['answer']=translink('survey', $oldsid, $newsid, $answerrowdata['answer']);
  1691. $newvalues=array_values($answerrowdata);
  1692. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1693. $ainsert = "INSERT INTO {$dbprefix}answers (".implode(',',array_keys($answerrowdata)).") VALUES (".implode(',',$newvalues).")";
  1694. $ares = $connect->Execute($ainsert) or $this->debugLsrc ("Error: ".": Failed to insert answer\n$ainsert\n".$connect->ErrorMsg());
  1695. }
  1696. }
  1697. }
  1698. $this->debugLsrc("wir sind in ".__FILE__." - ".__FUNCTION__." Line ".__LINE__.", OK ");
  1699. // Finally the question attributes - Is called just once and only if there was a question
  1700. if (isset($question_attributesarray) && $question_attributesarray) {//ONLY DO THIS IF THERE ARE QUESTION_ATTRIBUES
  1701. $fieldorders =convertCSVRowToArray($question_attributesarray[0],',','"');
  1702. unset($question_attributesarray[0]);
  1703. foreach ($question_attributesarray as $qar) {
  1704. $fieldcontents=convertCSVRowToArray($qar,',','"');
  1705. $qarowdata=array_combine($fieldorders,$fieldcontents);
  1706. $qarowdata["qid"]=$newqid;
  1707. unset($qarowdata["qaid"]);
  1708. $newvalues=array_values($qarowdata);
  1709. $newvalues=array_map(array(&$connect, "qstr"),$newvalues); // quote everything accordingly
  1710. $qainsert = "INSERT INTO {$dbprefix}question_attributes (".implode(',',array_keys($qarowdata)).") VALUES (".implode(',',$newvalues).")";
  1711. $result=$connect->Execute($qainsert) or $this->debugLsrc ("Couldn't insert question_attribute$qainsert".$connect->ErrorMsg());
  1712. }
  1713. }
  1714. }
  1715. $this->debugLsrc("wir sind in - ".__FUNCTION__." Line ".__LINE__.", FERTIG ");
  1716. // CONDITIONS is DONE
  1717. return array('gid'=>$newgid,'qid'=>$newqid);
  1718. //return $newgid;
  1719. }
  1720. /**
  1721. * function to delete a Survey with all questions and answersand Tokentable....
  1722. *
  1723. * @param int $surveyid
  1724. * @return boolean
  1725. */
  1726. function deleteSurvey($surveyid)
  1727. {
  1728. global $connect ;
  1729. global $dbprefix ;
  1730. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  1731. include("lsrc.config.php");
  1732. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", OK ");
  1733. $tablelist = $connect->MetaTables();
  1734. $dict = NewDataDictionary($connect);
  1735. if (in_array("{$dbprefix}survey_$surveyid", $tablelist)) //delete the survey_$surveyid table
  1736. {
  1737. $dsquery = $dict->DropTableSQL("{$dbprefix}survey_$surveyid");
  1738. //$dict->ExecuteSQLArray($sqlarray);
  1739. $dsresult = $dict->ExecuteSQLArray($dsquery);
  1740. }
  1741. if (in_array("{$dbprefix}tokens_$surveyid", $tablelist)) //delete the tokens_$surveyid table
  1742. {
  1743. $dsquery = $dict->DropTableSQL("{$dbprefix}tokens_$surveyid");
  1744. $dsresult = $dict->ExecuteSQLArray($dsquery) or $this->debugLsrc ("Couldn't \"$dsquery\" because ".$connect->ErrorMsg());
  1745. }
  1746. $dsquery = "SELECT qid FROM {$dbprefix}questions WHERE sid=$surveyid";
  1747. $dsresult = db_execute_assoc($dsquery) or $this->debugLsrc ("Couldn't find matching survey to delete: \n $dsquery \n".$connect->ErrorMsg());
  1748. while ($dsrow = $dsresult->FetchRow())
  1749. {
  1750. $asdel = "DELETE FROM {$dbprefix}answers WHERE qid={$dsrow['qid']}";
  1751. $asres = $connect->Execute($asdel);
  1752. $cddel = "DELETE FROM {$dbprefix}conditions WHERE qid={$dsrow['qid']}";
  1753. $cdres = $connect->Execute($cddel) or die();
  1754. $qadel = "DELETE FROM {$dbprefix}question_attributes WHERE qid={$dsrow['qid']}";
  1755. $qares = $connect->Execute($qadel);
  1756. }
  1757. $qdel = "DELETE FROM {$dbprefix}questions WHERE sid=$surveyid";
  1758. $qres = $connect->Execute($qdel);
  1759. $scdel = "DELETE FROM {$dbprefix}assessments WHERE sid=$surveyid";
  1760. $scres = $connect->Execute($scdel);
  1761. $gdel = "DELETE FROM {$dbprefix}groups WHERE sid=$surveyid";
  1762. $gres = $connect->Execute($gdel);
  1763. $slsdel = "DELETE FROM {$dbprefix}surveys_languagesettings WHERE surveyls_survey_id=$surveyid";
  1764. $slsres = $connect->Execute($slsdel);
  1765. $srdel = "DELETE FROM {$dbprefix}surveys_permissions WHERE sid=$surveyid";
  1766. $srres = $connect->Execute($srdel);
  1767. $srdel = "DELETE FROM {$dbprefix}saved_control WHERE sid=$surveyid";
  1768. $srres = $connect->Execute($srdel);
  1769. $sdel = "DELETE FROM {$dbprefix}surveys WHERE sid=$surveyid";
  1770. $sres = $connect->Execute($sdel);
  1771. $surveyid=false;
  1772. return true;
  1773. }
  1774. /**
  1775. * This function pulls a CSV representation of the Field map
  1776. *
  1777. * @param mixed $surveyid - the survey ID you want the Fieldmap for
  1778. * @return String $fieldmap
  1779. */
  1780. function FieldMap2CSV($surveyid)
  1781. {
  1782. $fields=array("fieldname", "type", "sid", "gid", "qid", "aid",'title','question','group_name','lid','lid1');
  1783. $fieldmap=createFieldMap($surveyid,'full');
  1784. $result='"'.implode('","',$fields).'"'."\n";
  1785. foreach ($fieldmap as $entry)
  1786. {
  1787. $destfieldmap=array();
  1788. foreach ($fields as $field)
  1789. {
  1790. if (isset($entry[$field]))
  1791. {
  1792. $destfieldmap[$field]=$entry[$field];
  1793. }
  1794. else
  1795. {
  1796. $destfieldmap[$field]='';
  1797. }
  1798. }
  1799. $entry=array_map('CSVEscape',array_values($destfieldmap));
  1800. $result.=implode(',',$entry)."\n";
  1801. }
  1802. return $result;
  1803. }
  1804. function sendStatistic($surveyid, $to, $tempFile, $html=null)
  1805. {
  1806. include("lsrc.config.php");
  1807. global $sitename;
  1808. global $clang;
  1809. if($tempFile==null && isset($html))
  1810. {
  1811. $css = "<style type='text/css'>"
  1812. ."table.statisticstable, table.statisticssummary {
  1813. background-color:#EEF6FF;
  1814. border-collapse:collapse;
  1815. border-width: 0px;
  1816. border-style: none;
  1817. }
  1818. .statisticssummary thead th
  1819. {
  1820. background:#D2E0F2;
  1821. }
  1822. .statisticssummary th:first-child,
  1823. .statisticstable td:first-child {
  1824. text-align:right;
  1825. }
  1826. .statisticssummary thead th:first-child
  1827. {
  1828. text-align:center;
  1829. }
  1830. .statisticssummary th, .statisticssummary td, .statisticstable td {
  1831. padding:3px 10px;
  1832. }
  1833. .statisticstable tr {
  1834. border-color: #fff;
  1835. border-style: solid;
  1836. border-width: 1px;
  1837. }
  1838. .statisticstable thead th
  1839. {
  1840. background:#D2E0F2;
  1841. text-align:center;
  1842. color:#1D2D45;
  1843. padding:4 10px;
  1844. }
  1845. .statisticstable tfoot tr {
  1846. background:#D2E0F2;
  1847. text-align:center;
  1848. }"
  1849. ."</style>";
  1850. $message = sprintf($clang->gT("This is your personal statistic sheet for survey #%s"),$css."<center>".$message.$surveyid."<br/>".$html."</center>");
  1851. return SendEmailMessage($message, sprintf($clang->gT("Statistics Survey #%s"),$surveyid), $to, getBounceEmail($surveyid), $sitename, true);
  1852. }
  1853. else
  1854. {
  1855. $message = sprintf($clang->gT("This is your personal statistic sheet for survey #%s"),$surveyid);
  1856. return SendEmailMessage($message, sprintf($clang->gT("Statistics Survey #%s"),$surveyid), $to , getBounceEmail($surveyid), $sitename, $ishtml, getBounceEmail($surveyid), $tempFile);
  1857. }
  1858. }
  1859. private function getqtypelist($SelectedCode = "T", $ReturnType = "array")
  1860. {
  1861. include("lsrc.config.php");
  1862. global $publicurl;
  1863. //global $sourcefrom, $clang;
  1864. $qtypes = array(
  1865. "1"=>"Array (Flexible Labels) Dual Scale",
  1866. "5"=>"5 Point Choice",
  1867. "A"=>"Array (5 Point Choice)",
  1868. "B"=>"Array (10 Point Choice)",
  1869. "C"=>"Array (Yes/No/Uncertain)",
  1870. "D"=>"Date",
  1871. "E"=>"Array (Increase, Same, Decrease)",
  1872. "F"=>"Array (Flexible Labels)",
  1873. "G"=>"Gender",
  1874. "H"=>"Array (Flexible Labels) by Column",
  1875. "I"=>"Language Switch",
  1876. "K"=>"Multiple Numerical Input",
  1877. "L"=>"List (Radio)",
  1878. "M"=>"Multiple choice",
  1879. "N"=>"Numerical Input",
  1880. "O"=>"List With Comment",
  1881. "P"=>"Multiple choice with comments",
  1882. "Q"=>"Multiple Short Text",
  1883. "R"=>"Ranking",
  1884. "S"=>"Short Free Text",
  1885. "T"=>"Long Free Text",
  1886. "U"=>"Huge Free Text",
  1887. "W"=>"List (Flexible Labels) (Dropdown)",
  1888. "X"=>"Boilerplate Question",
  1889. "Y"=>"Yes/No",
  1890. "Z"=>"List (Flexible Labels) (Radio)",
  1891. "!"=>"List (Dropdown)",
  1892. ":"=>"Array (Multi Flexible) (Numbers)",
  1893. ";"=>"Array (Multi Flexible) (Text)",
  1894. );
  1895. asort($qtypes);
  1896. if ($ReturnType == "array")
  1897. {return $qtypes;}
  1898. }
  1899. /**
  1900. * This function removes the UTF-8 Byte Order Mark from a string
  1901. *
  1902. * @param string $str
  1903. * @return string
  1904. */
  1905. private function removeBOM($str=""){
  1906. if(substr($str, 0,3) == pack("CCC",0xef,0xbb,0xbf)) {
  1907. $str=substr($str, 3);
  1908. }
  1909. return $str;
  1910. }
  1911. /**
  1912. * create a token table for the given survey id
  1913. * @param $iVid
  1914. * @return unknown_type
  1915. */
  1916. function createTokenTable($iVid, $att=0)
  1917. {
  1918. global $connect;
  1919. global $dbprefix;
  1920. global $databasetabletype;
  1921. global $databasetype;
  1922. global $rootdir;
  1923. global $defaultlang;
  1924. include("lsrc.config.php");
  1925. require_once($rootdir.'/classes/core/language.php');
  1926. $clang = new limesurvey_lang($defaultlang);
  1927. // check if the Token table already exists, if not, create it...
  1928. if(!db_tables_exist("{$dbprefix}tokens_".$iVid))
  1929. {
  1930. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Token Table existiert nicht ");
  1931. $createtokentable =
  1932. "tid int I NOT NULL AUTO PRIMARY,\n "
  1933. . "firstname C(40) ,\n "
  1934. . "lastname C(40) ,\n ";
  1935. //MSSQL needs special treatment because of some strangeness in ADODB
  1936. if ($databasetype == 'odbc_mssql' || $databasetype == 'odbtp' || $databasetype == 'mssql_n' || $databasetype == 'mssqlnative')
  1937. {
  1938. $createtokentable.= "email text ,\n "
  1939. ."emailstatus text ,\n ";
  1940. }
  1941. else
  1942. {
  1943. $createtokentable.= "email text ,\n "
  1944. ."emailstatus text ,\n ";
  1945. }
  1946. $createtokentable.= "token C(36) ,\n "
  1947. . "language C(25) ,\n "
  1948. . "sent C(17) DEFAULT 'N',\n "
  1949. . "remindersent C(17) DEFAULT 'N',\n "
  1950. . "remindercount int I DEFAULT 0,\n "
  1951. . "completed C(17) DEFAULT 'N',\n "
  1952. . "validfrom date ,\n "
  1953. . "validuntil date ,\n "
  1954. . "mpid I ";
  1955. $tabname = "{$dbprefix}tokens_{$iVid}"; # not using db_table_name as it quotes the table name (as does CreateTableSQL)
  1956. $taboptarray = array('mysql' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci',
  1957. 'mysqli' => 'ENGINE='.$databasetabletype.' CHARACTER SET utf8 COLLATE utf8_unicode_ci');
  1958. $dict = NewDataDictionary($connect);
  1959. $sqlarray = $dict->CreateTableSQL($tabname, $createtokentable, $taboptarray);
  1960. $execresult = $dict->ExecuteSQLArray($sqlarray, false);
  1961. $createtokentableindex = $dict->CreateIndexSQL("{$tabname}_idx", $tabname, array('token'));
  1962. $dict->ExecuteSQLArray($createtokentableindex, false);
  1963. if($execresult!=0)
  1964. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", token table created ");
  1965. else
  1966. {
  1967. $this->debugLsrc("WARNING: ".__FUNCTION__." Line ".__LINE__.", token table NOT created ");
  1968. $this->debugLsrc($createtokentable);
  1969. while(list($key, $value)= each($sqlarray) )
  1970. {
  1971. $this->debugLsrc("$key - $value");
  1972. }
  1973. }
  1974. $n=1;
  1975. while($att>=$n)
  1976. {
  1977. $sql = "ALTER TABLE {$dbprefix}tokens_$iVid ADD COLUMN attribute_$n VARCHAR(255); ";
  1978. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Attribute_$n anlegen ,sql: $sql");
  1979. //modify_database("","$sql");
  1980. $connect->Execute($sql);
  1981. ++$n;
  1982. }
  1983. }
  1984. return;
  1985. }
  1986. /**
  1987. * The new one...
  1988. * * Function to insert Participant data while auto creating token if non is supported...
  1989. * @param $sUser
  1990. * @param $sPass
  1991. * @param $iVid
  1992. * @param $sParticipantData (FIRSTNAME;LASTNAME;EMAIL;LANG;TOKEN;VALIDFROM;VALIDTO;attrib1,attrib2,attrib3,attrib4,attrib5::)
  1993. * @return unknown_type
  1994. */
  1995. function insertParticipants($iVid, $sParticipantData)
  1996. {
  1997. global $connect ;
  1998. global $dbprefix ;
  1999. $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC;
  2000. include("lsrc.config.php");
  2001. //$this = new lsrcHelper();
  2002. // check for appropriate rights
  2003. // if(!$this->checkUser($sUser, $sPass))
  2004. // {
  2005. // throw new SoapFault("Authentication: ", "User or password wrong");
  2006. // exit;
  2007. // }
  2008. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", $iVid, $sParticipantData ");
  2009. // check if there is a $iVid, else abort
  2010. if(!isset($iVid) || $iVid=='' || $iVid==0 )
  2011. {
  2012. return 0;
  2013. }
  2014. // check if the Survey we want to populate with data and tokens already exists, else -> Fault
  2015. if(!$this->surveyExists($iVid))
  2016. {
  2017. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", survey does not exist ");
  2018. return 0;
  2019. }
  2020. $this->createTokenTable($iVid);
  2021. //set the Seperators to default if nothing is set in the lsrc.config.php
  2022. if(!isset($sDatasetSeperator) || $sDatasetSeperator=='')
  2023. {$sDatasetSeperator = "::";}
  2024. if(!isset($sDatafieldSeperator) || $sDatafieldSeperator=='')
  2025. {$sDatafieldSeperator = ";";}
  2026. // prepare to fill the table lime_tokens_*
  2027. // this is sensitiv, if the Seperator is not the defined one, almost everything could happen, BE AWARE OF YOUR SEPERATOR!...
  2028. $asDataset = explode($sDatasetSeperator, $sParticipantData);
  2029. // write the tokens to the token_table
  2030. $iCountParticipants = count($asDataset);
  2031. $iInsertedParticipants=0;
  2032. foreach($asDataset as $sData)
  2033. {
  2034. //some extra sql statement comes in here later
  2035. $attributes='';
  2036. $attributesData='';
  2037. $validity='';
  2038. $validityData='';
  2039. if($sData!='')
  2040. {
  2041. $asDatafield = explode($sDatafieldSeperator, $sData);
  2042. $checkCnt=1;
  2043. $iDataLength = count($asDatafield);
  2044. for($n=0;$n>=$iDataLength;++$n)
  2045. {
  2046. if($asDatafield[$n]=='')
  2047. {
  2048. $asDatafield[$n]=null;
  2049. }
  2050. }
  2051. // token generieren
  2052. while($checkCnt>0)
  2053. {
  2054. $value = sRandomChars(10); //change sRandomChars value for different tokenlength (up to 36 chars max.)
  2055. $cQuery= "select token from ".$dbprefix."tokens_".$iVid." where token = '".$value."'; ";
  2056. $result = db_execute_assoc($cQuery);
  2057. $checkCnt = $result->RecordCount();
  2058. }
  2059. if(!isset($asDatafield[4]) || $asDatafield[4]=='')
  2060. {
  2061. $asDatafield[4]= $value;
  2062. }
  2063. //set session language if no language is set
  2064. if(!isset($asDatafield[3]) || $asDatafield[3]=='')
  2065. {
  2066. $asDatafield[3] = $_SESSION['lang'];
  2067. }
  2068. //Begin to prepare our statement here. One array for the columns to insert and a parallel array with the values.
  2069. $insertColumns = array('firstname', 'lastname', 'email', 'language', 'token');
  2070. $insertValues = array($asDatafield[0], $asDatafield[1], $asDatafield[2], $asDatafield[3], $asDatafield[4]);
  2071. if(isset($asDatafield[5]) && $asDatafield[5]!=null)
  2072. {
  2073. //$validity .= ',validfrom';
  2074. //$validityData .=",'$asDatafield[5]'";
  2075. $insertColumns[] = 'validfrom';
  2076. $insertValues[] = $asDatafield[5];
  2077. }
  2078. if(isset($asDatafield[6]) && $asDatafield[5]!=null)
  2079. {
  2080. //$validity .= ',validuntil';
  2081. //$validityData .=",'$asDatafield[6]'";
  2082. $insertColumns[] = 'validuntil';
  2083. $insertValues[] = $asDatafield[6];
  2084. }
  2085. if(isset($asDatafield[7]) && $asDatafield[7]!='')
  2086. {
  2087. $asAttributes = explode(",", $asDatafield[7]);
  2088. $n=0;
  2089. foreach($asAttributes as $attribute)
  2090. {
  2091. ++$n;
  2092. //$check = "SELECT attribute_$n FROM {$dbprefix}_tokens_$iVid ";
  2093. $sql = "ALTER TABLE {$dbprefix}tokens_$iVid ADD COLUMN attribute_$n VARCHAR(255); ";
  2094. //$attributes.=",attribute_$n";
  2095. //$attributesData.= ",'$attribute'";
  2096. $insertColumns[] = "attribute_$n";
  2097. $insertValues[] = $attribute;
  2098. $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Attribute_$n mit $attribute anlegen ,sql: $sql");
  2099. //modify_database("","$sql");
  2100. $connect->Execute($sql);
  2101. }
  2102. }
  2103. /*$sInsertParti = "INSERT INTO ".$dbprefix."tokens_".$iVid
  2104. ."(firstname,lastname,email,token,"
  2105. ."language $validity $attributes) "
  2106. ."VALUES ('{$asDatafield[0]}', '{$asDatafield[1]}' , '{$asDatafield[2]}', '{$asDatafield[4]}' , "
  2107. ."'{$asDatafield[3]}' $validityData $attributesData) ";*/
  2108. $sInsertParti = "INSERT INTO {$dbprefix}tokens_$iVid (".implode(',', $insertColumns).") VALUES (".trim(str_repeat('?,', count($insertColumns)), ',').");";
  2109. $this->debugLsrc("$sInsertParti");
  2110. // $sInsertParti = "INSERT INTO ".$dbprefix."tokens_".$iVid
  2111. // ."(firstname,lastname,email,emailstatus,token,"
  2112. // ."language,sent,completed,attribute_1,attribute_2,mpid)"
  2113. // ."VALUES ('".$asDatafield[0]."' ,
  2114. // '".$asDatafield[1]."' , '".$asDatafield[2]."' , 'OK' , '".$asDatafield[5]."',
  2115. // '".$_SESSION['lang']."', 'N', 'N', '".$asDatafield[3]."' , '".$asDatafield[4]."' , NULL); ";
  2116. //
  2117. if($connect->Execute($sInsertParti, $insertValues))
  2118. {
  2119. ++$iInsertedParticipants;
  2120. // check participants eMail status and set it
  2121. // see http://data.iana.org/TLD/tlds-alpha-by-domain.txt
  2122. $maxrootdomainlength = 32;
  2123. if(1==preg_match("/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*\.(([0-9]{1,3})|([a-zA-Z]{2,".$maxrootdomainlength."}))$/ix", $asDatafield[2]))
  2124. $this->changeTable("tokens_".$iVid,"emailstatus","OK","email='{$asDatafield[2]}'");
  2125. // if(isset($asDatafield[7]) && $asDatafield[7]!='')
  2126. // {
  2127. // $asAttributes = explode(",", $asDatafield[7]);
  2128. // $n=0;
  2129. // foreach($asAttributes as $attribute)
  2130. // {
  2131. //
  2132. // ++$n;
  2133. // //$check = "SELECT attribute_$n FROM {$dbprefix}_tokens_$iVid ";
  2134. //
  2135. // $sql = "ALTER TABLE {$dbprefix}tokens_$iVid ADD COLUMN attribute_$n VARCHAR(255); ";
  2136. // $attributes.=",attribute_$n";
  2137. // $attributesData.= ",'$attribute'";
  2138. //
  2139. // $this->debugLsrc("wir sind in ".__FUNCTION__." Line ".__LINE__.", Attribute_$n mit $attribute anlegen ,sql: $sql");
  2140. // //modify_database("","$sql");
  2141. // $connect->Execute($sql);
  2142. //
  2143. //
  2144. // $insert = "UPDATE {$dbprefix}tokens_$iVid "
  2145. // . " SET attribute_$n='$attribute' WHERE token='$asDatafield[4]' ";
  2146. //
  2147. // $this->debugLsrc("$insert");
  2148. // $connect->Execute($insert);
  2149. // }
  2150. // }
  2151. }
  2152. }
  2153. }
  2154. return "".$iCountParticipants."Datasets given, ".$iInsertedParticipants." rows inserted. ";
  2155. }
  2156. }