Actions

ExpressionScript - presentation/ja

From LimeSurvey Manual

Revision as of 01:23, 20 October 2018 by Bravehorse (talk | contribs) (Created page with "XSSを有効にすると、式マネージャーシステムの一部がつかえなくなります。 * 式でHTMLタグを開き、別の式...")



はじめに

LimeSurveyでは、新しいExpression Manager(EM)モジュールを使用して、より複雑な分岐、評価、検証、およびカスタマイズがサポートされています。LimeSurveyがサーバー内で行う置換、条件評価の管理方法を置き換えることができます。また、ランタイムデータベースの読み込みのほとんどが不要になるため、処理速度が大幅に向上します。EMはDr. Thomas White(TMSWhite)が開発しました。


主な定義

  1. :  中括弧で囲まれたもの
    • 開く中括弧の直後または閉じる中括弧の直前に空白がない
    • 式の内容はEMが評価するため、数式、関数、複雑な文字列と日付処理を含めることができます。
  2. 文言調整: "パイピング"とも呼ばれますが、これは条件付きでテキストを変更するプロセスです。
    • すべての'置換フィールド'、参加者データ、回答データにアクセスできます。
    • 質問、回答、およびそのプロパティにも簡単にアクセスできます。
  3. 出現条件式:  質問を表示するかを制御する新しい質問属性
    • 出現条件式がある場合、その出現条件が真と評価された場合にのみ質問が表示されます。
    • 内部では、すべてのarray_filterコマンドとarray_filter_excludeコマンドがサブ質問レベルの出現条件になります。
  4. SGQA:  LimeSurvey <= 1.91+で変数の命名に使われているものです。
    • Survey(アンケート)-Group(グループ)-Question(質問)-Answer(回答)の略です。
    • SGQA変数は123X5X382X971のようなもので、サブ質問の接尾辞がつくことがあります。
    • これらの変数はベースとなるS/Q/G/Aデータベースコードに固有のもので、変更する必要があることが良くあります。
  5. 質問タイプ:  データベースに計算やレポートを保存する新しい質問タイプ
    • これはテキストを表示する質問のようなものですが、"この質問をいつも隠す"を設定しても、その内容はデータベースに保存されます。
  6. 質問コード:  EMでの使用が推奨される変数名
    • これは質問の目的を示すわかりやすい名前にすることができ、複雑なロジックを読みやすくなります。
    • 質問コードは数字で始めることはできないので、質問番号を質問コードにするときは、単に"q1"、"q1a"、"g1q2"のようにしてください。
    • 現在のところ、データをSPSSまたはRにエクスポートすると、これが変数名になります。したがって、統計分析を行う場合は、ユニークにしなければなりません。


EMを使わなければならないのか?

短い答えは"いいえ"ですが、作成するアンケートがどれだけ複雑かによって変わります。

例えば、条件エディターでは、アンケートの質問に適用できるいくつかの基本的な式を扱います。ただし、条件エディタには制限があります。EMが使用されているのはこのためです。EMがカスタマイズの可能性を広げています。


条件と出現条件式の両方を使えるか?

はい。質問によって条件エディターを使用することも、出現条件式を使用することもできます。

条件と式の両方を同じ質問で設定することはできません。 条件が設定されると、出現条件のフィールドに書き込まれた式は使われません。さらに、出現条件式フィールドは手動では編集できません。

しかし、質問内で式と条件の両方を使用する方法があります。上で述べたように、条件式は出現条件式のフィールドを置き換えます。完了したら、新しく作成された式を確認し、テキストエディターにコピーします。条件エディターで作成した条件を削除し、残りの式と一緒にテキストエディターにコピーした条件ベースの式を追加して質問を編集します。


条件と関連のどちらを選ぶべきか?

各々の長所と短所のリストを以下に示します。

スタイル 長所 短所
条件 1. シンプルな条件を作成するための優れたGUI
2. サポートチームにより文書化され理解しやすいGUI
1. 簡単な比較のみをサポートし、"AND"/"OR"条件はうまく機能しない
2. 条件を入れ子にした場合の動作が不安定
3. データベースアクセスが遅く、アンケートに時間がかかる
4. 条件のリロードで不具合がレポートされている
5. GUIに拡張性がなく、何十、何百、または何千もの質問があるときにうまくいかない
6. SGQA名を使用しなければならないので、紙ベースのアンケートを変換するのが遅いかもしれない
7. 複雑な分岐が必要な場合、カスタムコードロジックを書くプログラマーが必要なことがある
出現条件 1. 80以上の関数と数学/文字列演算子を含む非常に複雑なロジックのサポート
2. 入れ子のロジックの完全サポート
3. 高速 - 余計なデータベースアクセスがなく、1000以上の質問があるアンケートをサポート
4. SGQAコードを必要としないため、リロードロジックで問題が生じない
5. 構文ハイライト機能は1000以上の質問があるアンケートにも対応
6. 既存の紙ベースのアンケートの電子化に簡単かつ迅速に対応
7. プログラマーを必要とせずに半構造化インタビューや疫学調査を容易にサポート
1. 単純な条件のためのGUIがない(代わりに構文ハイライト機能を使用)


注意:
  • ニーズに合ったものを使用することをお勧めします。
  • EM機能の詳細については、次のリンクをクリックしてください。


はじめに

式マネージャーを始める最善の方法は以下のとおりです。

  • http://www.limesurvey.org/en/download からLimeSurveyの最新の安定版をインストールしてください。
  • サンプルアンケートをインポートして確認します。
  • 使用例と使用法ステップバイステップの例を読んでください。
  • EMに関するドキュメント(このページ)を読んでください。
    • 分離された式の単体テスト(上級)
      • すべてのEM関数と演算子、PHPとJavaScriptの結果の使用例を表示します。
      • PHPとJavaScriptのバージョンで異なる結果を生成する関数はほとんどありません。このページの内容を踏まえ、EMロジックを適切に計画することができます。


用語

これらの単語は、EMの機能を記述するために一般的に使用されます。

  • 出現条件に基づく分岐 - 質問が出現条件を満たす場合は質問し、満たさない場合は質問しません(非表示となり、データベース内ではNULLとして格納されます)。質問エディターパネルと質問グループエディターパネルに出現条件フィールドがあります。後者では、各質問に同じ条件をコピーしたり、グループと質問レベルの条件付きロジックを組み合わせたりせずに、一連の条件をグループ全体に適用するために使用されます。
  • 文言調整 - どの質問を表示すべきか決めたら、文言調整(パイピングとも呼ぶ)でどのように質問するかを指定します。これは簡単な置換(例: {TOKEN:FIRSTNAME})だけでなく、回答者が回答した性別、数に基づいて、動詞や名詞を変化させることもできます。また、アンケート回答者が回答したか(またはどのように回答したか)に基づいて、アンケート回答者に送信するメッセージを変更することもできます。
  • - EMでは、という新しい質問タイプを追加され、式の結果が格納されます。式はページ内で非表示であっても結果が計算され、データベースに書き込まれます。したがって、非表示のまま行うスコア計算、複雑な式に基づくナビゲーション、評価、データベース内に作成・格納されるレポートに使用されます。


出現条件とカスケードされた出現条件

すべての質問タイプで、質問が表示されるかどうかを制御する出現条件オプション が追加されました。EMは、アンケートに登場する順に出現条件式を処理します。式が真(または式がない - 古い形式のアンケート向け)の場合、質問が表示されます。出現条件式が偽の場合、質問は非表示になり、その値はデータベースでNULLになります。グループに出現条件を満たす質問がない場合、グループ全体がスキップされます。

さらに、式に含まれる変数のいずれかの出現条件が偽の場合、式は常に偽と評価されます。これにより出現条件の入れ子が可能になり、各々の質問に対して非常に長い出現条件の式を書く必要がなくなります。

たとえば、5つの質問Q1〜Q5があり、Q1が答えられたらQ2、Q2に答えられたらQ3などを表示したいとします。出現条件の式は次のようになります。

質問コード 出現条件 質問
Q1 1 名前は何ですか。
Q2 Q1 {Q1}さん、何歳ですか。
Q3 Q2 {Q2}歳なのですね。結婚していますか。
Q4 Q3 == "Y" {Q1}さん、結婚して何年になりますか。
Q5 Q4 {Q1}さん、子供は何人いますか。


グループレベルの出現条件

Expression Managerはグループレベルの関連性もサポートしています。これにより、ループの実装が容易になります。最大10のエンティティ(製品や家族など)から情報を収集したい場合、(家族の人数を答えさせたり、長いリストから好きな製品を選択させたりして)繰り返しが必要なエンティティの数を最初に判断します。エンティティの数がわかったら、10こある繰り返し用グループごとに{count >= 1}, {count >=2}, ... {count >= 10}のようにグループレベルの出現条件を設定します。各々のグループ内では、質問レベルの条件付きロジック(例:各々のエンティティの性別や年齢に基づく質問)を作成できます。質問とグループレベルの出現条件の式は、表示すべきかを決定するためにAND演算されます。

例を確認するには、次のアンケートをインポートします。国勢調査の例

以下のスクリーンショットでは、回答者が少なくとももう1人の同居者と一緒に住んでいる場合、グループPerson 1が表示されている(出現条件を満たしている)ことがわかります。



カスタマイズ/パイプ

中括弧内のものはすべて式として扱われるようになりました(後述する例外が1つあります)。式はすべてのLimeReplacementFields、すべての変数(いくつかのエイリアスを介して)、すべての一般的な演算子(数学、論理、比較)、数多くの関数(クライアント側でも動的に機能する)にアクセスします。

これらの式を使用すると、次のようなことができます。

  1. 先行する質問への回答に基づいて文言調整されたメッセージを回答者に表示する
  2. 評価を作成し、その結果に基づいて評価結果を表示する(条件付きで分岐、またはメッセージを表示する)(評価モジュール自体は使用しない)
  3. 質問、回答、およびレポート内の動詞、名詞を変化させる
  4. アンケートの最後で、"回答を表示する"ページの前に回答の要約を表示する


と呼ばれる新しい質問タイプがあります。これは、表示されている値をデータベースに格納することを除き、テキスト表示質問タイプと似ています。したがって、式の質問テキストに評価計算が含まれている場合、パブリックまたはプライベート統計情報内に表示できる変数の値がデータベースに格納されます。


構文

中カッコ内に含まれるものはすべて式と見なされます(ただし、先頭または末尾に空白がないことが必要です。これは、式マネージャーが埋め込みJavaScriptを処理しないようにするためです)。

開く括弧の後、閉じる括弧の前に空白がない限り、式は複数の行にまたがっても構いません。特に次のような入れ子のif()構文が見やすくなります。

{if(is_empty(PFTotals),
 '',
 if(PFTotals >= -5 && PFTotals <= -4,
   'Very Soft',
   if(PFTotals >= -3 && PFTotals <= -2,
     'Soft',
     if(PFTotals == -1,
       'Somewhat Soft',
       if(PFTotals == 0,
         'Moderate',
         if(PFTotals == 1,
           'Somewhat Hard',
           if(PFTotals >= 2 && PFTotals <= 3,
             'Hard',
             if(PFTotals >= 4 && PFTotals <= 5,
               'Very Hard',
               ''
             )
           )
         )
       )
     )
   )
 )
)}

式マネージャは、次の構文をサポートしています。

  • 標準的な数学演算子(例: +,-,*,/,!)
  • 標準的な比較演算子(例: <,<=,==,!=,>,>=, およびこれらと同じ意味を持つlt, le, eq, ne, gt, ge)
  • かっこ(入れ子の式をグループ化できます)
  • 条件演算子(例: &&, | | およびこれらと同じ意味を持つand, or)
  • シングルまたはダブルクオートで囲まれた文字列(別のクオート記号で囲まれた文字列を含めることができます)
  • コンマ演算子(式のリストを持ち、最終結果を返します)
  • 代入演算子(=)
  • 定義済み変数(質問、質問属性、回答を参照する) - 例: SGQAコード
  • 定義済み関数(80以上あり、簡単に追加できます)


演算子

EM構文は、通常の演算子の優先順位に従います。

レベル 演算子 説明
1 () グループ化または関数呼び出しのための括弧
2 ! - + 単項演算子: 否定、正負
3 * / 乗算、除算
4 + - 加算、減算
5 < <= > >= lt le gt ge 比較演算子
6 == != eq ne 同等比較
7 and 論理積 AND
8 or 論理和 OR
9 = 代入演算子
10 , コンマ演算子
JavaScriptとPHPの間の一貫性を保つために、プラス演算子(+)は両方のオペランドが数値の場合は加算を行いますが、両方の部分が数値以外の文字列の場合は連結します。しかし、意図をもっとはっきりさせるため、連結関数join()を使うことをお勧めします。文字列を期待しているのに数値となったり、その逆となったりすることも防止します。


代入演算子(=)を使用する際の注意

代入演算子は、予期しない副作用を引き起こす可能性があるため、どうしても必要な場合を除いて使用しないでください。たとえば、先行する質問の値を変更すると、その質問と現在の質問との間で入れ子となった出現条件と検証ロジックが再計算されないため、内部的に一貫性のないデータになることがあります(たとえば、NULLにすべきなのに回答がある、回答すべきだがスキップされる、等)。一般に、変数に値を割り当てる場合は、式の質問タイプを作成し、その値を設定する式を使用する必要があります。しかし、この演算子がまれに必要となるため用意されています。

この演算子について注意を促すため、構文式の中では赤いフォントで表示されています("=="と混同しないようにするため)。



代入演算子を使用する

代入演算子を使用する主な理由は次のとおりです。

  • 既定値を設定できない質問の既定値を式を使って設定する必要がある(ユーザーインターフェイスでは回答オプションの1つを選択できるが、式を入力することができないリスト、ラジオなど)。ただし、LimeSurveyは式がその質問に対する許容可能な回答を生成できるかどうかを検証できないため、注意して使用してください。
  • 後続の回答に基づいて先行する質問への回答を強制的に変更する必要がある
  • など...

この目的のために、式マネージャーシステムを使用することができます。この目的のため、を使用する方がよいでしょう。

例:

  • 質問への回答を小文字にする: {QCODE=strtolower(QCODE.NAOK)}
  • アンケートの開始時に配列質問タイプに既定の回答を設定する: {Q1_SQ1=(is_empty(Q1_SQ1.NAOK),"A99",Q1_SQ1.NAOK)}
  • アンケート開始時に配列テキストの質問タイプに対する既定の回答を設定する: {Q1_SQY1_SQX1 = (is_empty(Q1_SQY1_SQX1.NAOK),"Inserted answer", Q1_SQY1_SQX1.NAOK)}
  • 条件付きの回答を設定する: {QCODE=if(YesNo="Y","A1","")}


XSS セキュリティ

XSSを有効にすると、式マネージャーシステムの一部がつかえなくなります。

  • 式でHTMLタグを開き、別の式で閉じる
  • URL内で複雑な式を使用する


Please note that XSS is enabled by default in any LimeSurvey installation.


Examples and workarounds:

  • {if( 1 ,"<strong>","")}information{if( 1 ,"</strong>","")} is broken with XSS security, here you can use {if(1,"<strong>information</strong>","information")};
  • <a href="/script.php?value={if(QCODE == "Y","yes","no")}">next</a>, here you can use an equation question because using a complete question code is OK : <a href="/script.php?value={EQUATION.NAOK}">next</a>.


変数へのアクセス

Expression Manager provides read-only access to whichever variables you might need. For backwards compatibility, it provides access to the following:

  • TOKEN:xxx - the value of a TOKEN (e.g., TOKEN:FIRSTNAME, TOKEN:ATTRIBUTE_5) (only for not anonymous survey).
  • INSERTANS:SGQA - the display value of an answer (e.g., "Yes") - similar to using {QCODE.shown}.
  • All {XXX} values used by templates.
  • In question text, you can use {QID} replaced by the question id and {SGQ} replaced by the SGQA of the question.

In addition, Expression Manager lets you refer to variables by the Question Code (the 'title' column in the questions table within the database). This is also the variable label used when you export your data to SPSS, R, or SAS. For example, if you have questions about name, age, and gender, you could call those variables name, age, and gender instead of 12345X13X22, 12345X13X23, and 12345X13X24. This makes equations easier for everyone to read and validate the logic, plus making it possible to shuffle questions around without having to keep track of group or question numbers.

重要: 先行するページや質問で発生する変数を参照するのが安全です。

さらに、式マネージャーを使用すると、多くの質問プロパティにアクセスできます。


Syntax Meaning Example Example Result
Qcode an alias for Qcode.code {implode(',',name,gender)} 'Tom','M'
Qcode.code the selected response code for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {implode(',',name.code,gender.code)} 'Tom','M'
Qcode.NAOK same as Qcode - see discussion of NAOK {gender.NAOK} 'M'
Qcode.value the assessment value for the question if it is relevant (otherwise blank), or the text value if it is not a coded question {gender.value} '1'
Qcode.valueNAOK same as Qcode.value - see discussion about NAOK {gender.valueNAOK} '1'
Qcode.shown the display value for the question {implode(',',name.shown,gender.shown)} 'Tom','Male'
Qcode.question the text of the question {gender.question} 'What is your gender?'
Qcode.mandatory whether the question is mandatory (Y/N) {gender.mandatory} 'N'
Qcode.qid the internal question number (not the sequential number) {gender.qid} 337
Qcode.type the question type {gender.type} 'G'
Qcode.jsName the correct javascript name for the question, regardless whether declared on or off this page {gender.jsName} 'java1827X3X337'
Qcode.gid the internal group number (not the sequential number) {gender.gid} 3
Qcode.qseq the sequential number of the question, starting from 0 {gender.qseq} 5
Qcode.gseq the sequential number of the group, starting from 0 {gender.gseq} 1
Qcode.relevanceStatus whether the question is currently relevant (0 or 1) {gender.relevanceStatus} 1
Qcode.relevance the question-level relevance equation {gender.relevance} '!is_empty(name)'
Qcode.grelevance the  group-level relevance equation {gender.grelevance} 'num_children >= 5'
Qcode.sgqa the SGQA value for this question {gender.sgqa} '1827X3X337'


HTMLエディターの問題

HTMLエディターを使用すると、一部の文字がHTML実体に置き換えられます。

  • & → &amp;
  • < → &lt;
  • > → &gt;

HTMLエディターを使用する場合は、次のものを使用する必要があります。

  • & に対しては and
  • < に対してはlt
  • <= に対してはle
  • > に対してはgt
  • >= に対してはge


It is recommended to clear your expression of HTML that appears within your expression. If you use the LimeSurvey HTML editor, click on the "Source" button (located in the upper left part of the editor) and delete all the characters that are not related to your expression (e.g.,

,
, and so on).

Qcode変数の命名

Qcodeを構成する方法(およびいくつかのプロパティにアクセスする方法)の質問タイプ別の詳細は次のとおりです。一般に、Qcodeは次のように構成されます。

 QuestionCode . '_' . SubQuestionID . '_' . ScaleId

For comment and other, the corresponding question codes are QuestionCode_comment and QuestionCode_other, respectively.

Type Description Code SubQs Answer Options Scales Answer Code Answer Shown Relevance
5 5 Point Choice Radio-Buttons Q1 1-5 {Q1} {Q1.shown} {Q1==3}
B Array (10 Point Choice) Radio-Buttons Q2 L1-L6 1-10 {Q2_L2} {Q2_L2.shown} {Q2_L2==7}
A Array (5 Point Choice) Radio-Buttons Q3 1-5 1-5 {Q3_1} {Q3_1.shown} {Q3_1>=3}
1 Array (Flexible Labels) Dual Scale Q4 sq1-sq5 0:a1-a3 1:b1-b3 {Q4_sq1_0} {Q4_sq1_1.shown} {Q4_sq1_1=='b2'}
H Array (Flexible) - Column Format Q5 1-5 s,m,t {Q5_1} {Q5_1.shown} {Q5_1=='s'}
F Array (Flexible) - Row Format Q6 F1-F5 1-5 {Q6_F3} {Q6_F3.shown} {Q6_F3==4}
E Array (Increase/Same/Decrease) Radio-Buttons Q7 1-7 I,S,D {Q7_4} {Q7_4.shown} {Q7_4=='D'}
: Array (Multi Flexi) 1 To 10 Q8 ls1,todo,ls2 min,max,avg {Q8_ls1_max} {Q8_ls2_avg.shown} {Q8_ls2_min==7}
; Array (Multi Flexi) Text Q9 hp,st,sw 1st,2nd,3rd {Q9_hp_3rd} {Q9_hp_3rd.shown} {Q9_hp_3rd=='Peter'}
C Array (Yes/Uncertain/No) Radio-Buttons Q10 1-5 Y,N,U {Q10_1} {Q10_1.shown} {Q10_3=='Y'}
X Boilerplate Question Q11 {Q11.shown}
D Date Q12 {Q12} {Q12.shown}
* Equation Q13 {Q13} {Q13.shown} {Q13>5}
~124~ File Upload (records number of files uploaded) Q14 {Q14} {Q14>0}
G Gender Drop-Down List Q15 M,F {Q15} {Q15.shown} {Q15=='M'}
U Huge Free Text Q16 {Q16} {Q16.shown} {strlen(Q16)>100}
I Language Question Q17 {Q17} {Q17.shown} {Q17=='en'}
! List - Dropdown Q18 1-5 {Q18} {Q18.shown} {Q18==3}
L List Drop-Down/Radio-Button List Q19 A-Z {Q19} {Q19.shown} {Q19=='X'}
O List With Comment Drop-Down/Radio-Button List + Textarea Q20 A-F {Q20},{Q20comment} {Q20.shown} {Q20=='B'}
T Long Free Text Q21 {Q21} {Q21.shown} {strstr(Q21,'hello')>0}
M Multiple Choice Checkbox Q22 A-F, other {Q22_E}, {Q22_other} {Q22_E.shown}, {Q22_other.shown} {Q22_E=='Y'}
P Multiple Choice With Comments Checkbox + Text Q23 A-F {Q23_D}, {Q23_Dcomment} {Q23_D.shown} {!is_empty(Q23)}
K Multiple Numerical Question Q24 self,mom,dad {Q24_self} {Q24_self.shown} {Q24_self>30}
Q Multiple Short Text Q25 A-F {Q25_B} {Q25_B.shown} {substr(Q25_B,1,1)=='Q'}
N Numerical Question Type Q26 {Q26} {Q26.shown} {Q26 > 30}
R Ranking Style Q27 1-4 {Q27_1} {Q27_1.shown} {Q27_1==3}
S Short Free Text Q28 {Q28} {Q28.shown} {Q28=='mine'}
Y Yes/No Radio-Buttons Q29 {Q29} {Q29.shown} {Q29=='Y'}


NAOKの利用

NAOK --> "Not Applicable"(該当なし、NA)は問題ない(OK)


NAOKは、すべてまたは一部の変数が出現条件を満たさないということです。"Not Applicable"(該当なし、NA)は問題ない(OK)。

For example: count(Q1_SQ1,Q1_SQ2,Q1_SQ3,Q1_SQ4) give always an empty string if one subquestion of Q1 is filtered. To count the number of checked subquestion in such question can be count(Q1_SQ1.NAOK,Q1_SQ2.NAOK,Q1_SQ3.NAOK,Q1_SQ4.NAOK). If the subquestion is hidden, the EM returns an empty string.

NAOKがない場合、1つの質問または1つのサブ質問が非表示になっている場合、式マネージャーは常に空の文字列を返します(falseを返すのと同じです)。

.shownは常にNAOKの仕組み(非表示の時は空文字)を使っていますが、回答のコードが必要な場合は、質問コードの後に.NAOKを付加するとよいでしょう。それが必要で、内容を理解している場合は別です。

More information is provided in the Overriding Cascading Conditions subsection.


予約変数 "this"、"self"、"that"

回答されたサブ質問の数を数えたり、スコアを合計するなど、質問の全体を評価したい場合がよくあります。また、質問の特定の行や列(行や列の合計を取得してデータベースに格納するなど)を処理したい場合もあります。以下の予約変数により、そのプロセスを簡単に実現できます。


変数"This"

"this"変数は、"質問全体の検証式と"サブ質問の検証式"のオプションで排他的に使用されます(後者はGUIからは使えません)。該当の質問内の各セルの変数名に展開されます。したがって、各エントリが3より大きいかどうかを確認する場合は、"サブ質問の検証式"を(this > 3)に設定します。


変数"Self"

"self""that"変数はより強力で、式を処理する前に展開されるマクロとして機能します。"self"変数の構文は次のとおりです。

  • self
  • self.suffix
  • self.sub-selector
  • self.sub-selector.suffix
  1. suffixは、通常のqcode接尾辞のいずれかです(例: NAOK、value、shown)。
  1. sub-selector can be one of the following:
  • comments - only subquestions that are comments (e.g., multiple choice with comment and list with comment);
  • nocomments - only subquestions that are not comments;
  • sq_X - where X is a row or column identifier.  Only subquestions matching pattern X are selected. Note that search is done on complete code identifier, then sq_X match and include subquestions nX, X, Xn (e.g. if you use sq_1, subquestions a1, 1a, 1, 11 or 001 was included). Put attention at dual scale question type where subquestions code are QCODE_SQCODE_1 and QCODE_SQCODE_1 and to ranking question type where subquestions code are QCODE_1,QCODE_2 ....

例:

  • 質問に対して何らかの回答があったか? -> {count(self.NAOK)>0}
  • この質問の評価点数は? -> {sum(self.value)}

行と列の合計を取得することもできます。列A-Eと行1-5の数字の配列があるとします。

  • 総合計は? -> {sum(self.NAOK)}
  • 列Bの合計は? -> {sum(self.sq_B.NAOK)}
  • 行3の合計は? -> {sum(self.sq_3.NAOK)}


変数"That"

"that"は"self"に似ていますが、他の質問を参照することができます。構文は次のとおりです。

  • that.qname
  • that.qname.suffix
  • that.qname.sub-selector
  • that.qname.sub-selector.suffix

qnameは、サブ質問拡張がない質問の名前です。質問 'q1'を作成したら、それがqnameとなります。

例:

  • 質問q1に対して何らかの回答があったか? -> {count(that.q1.NAOK)>0}
  • q2の評価点数は? -> {sum(that.q2.NAOK)}
  • q3の総合計は? -> {sum(that.q3.NAOK)}
  • q4の列Cの合計は? -> {sum(that.q4.sq_C.NAOK)}
  • q4の行2の合計は? -> {sum(that.q4.sq_2.NAOK)}

"self"と"that"変数は、出現条件、検証、文言調整の式で使用できます。

注意すべき点は、ロジックファイルの表示機能を使用すると、"self"と"that"を展開した値が表示されることです。これにより、生成される実際の式が表示され、その結果、変数が存在することを検証できるようになります。かなり長い式になるかもしれないので、混乱しているように見えるかもしれません。しかし、質問を編集すると、"self"や"that"を使っている元の式が表示されます。

以下の場合は、これらの変数を使用しないでください。
  • 式に使用される各変数を明示的に命名する場合。
  • サブ質問を持たない変数を使用する場合(例:単一回答の質問)。そのような場合に、変数にプレフィックスとして"that"をつけると、予期しない結果が出る危険があります。


関数へのアクセス

式マネージャーでは、以下に示すように、数学関数、文字列関数、およびユーザー定義関数が利用できます。これらの関数にはPHPとJavaScriptに同等のものがあるので、サーバ側(PHP)とクライアント側(JavaScript)で同じように動作します。新しい機能を追加するのは簡単です。


実装済み関数

現在、以下の関数が利用可能です。

Function Meaning Syntax
abs Absolute value number abs(number)
acos Arc cosine number acos(number)
addslashes Quote string with slashes string addslashes(string)
asin Arc sine number asin(number)
atan Arc tangent number atan(number)
atan2 Arc tangent of two variables number atan2(number, number)
ceil Round fractions up number ceil(number)
checkdate Returns true(1) if it is a valid date in gregorian calendar bool checkdate(month,day,year)
convert_value Convert a numerical value using a inputTable and outputTable of numerical values number convert_value(fValue, iStrict, sTranslateFromList, sTranslateToList)
cos Cosine number cos(number)
count count the number of answered (non-blank)questions in the list number count(arg1, arg12, ..., argN)
countif Count the number of answered questions in the list equal the first argument number countif(matches, arg1, arg2, ... argN)
countifop Count the number of answered questions in the list which pass the criteria (arg op value) number countifop(op, value, arg1, arg2, ... argN)
date Format a local date/time string date(format [, timestamp=time()])
exp Calculates the exponent of e number exp(number)
fixnum Display numbers with comma as radix separator, if needed string fixnum(number)
floor Round fractions down number floor(number)
gmdate Format a GMT date/time string gmdate(format [, timestamp=time()])
html_entity_decode Convert all HTML entities to their applicable characters (always uses ENT_QUOTES and UTF-8) string html_entity_decode(string)
htmlentities Convert all applicable characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlentities(string)
expr_mgr_htmlspecialchars Convert special characters to HTML entities (always uses ENT_QUOTES and UTF-8) string htmlspecialchars(string)
expr_mgr_htmlspecialchars_decode Convert special HTML entities back to characters (always uses ENT_QUOTES and UTF-8) string htmlspecialchars_decode(string)
idate Format a local time/date as integer string idate(string [, timestamp=time()])
if Excel-style if(test,result_if_true,result_if_false) if(test,result_if_true,result_if_false)
implode Join array elements with a string string implode(glue,arg1,arg2,...,argN)
intval Get the integer value of a variable int intval(number [, base=10])
is_empty Determine whether a variable is considered to be empty bool is_empty(var)
is_float Finds whether the type of a variable is float bool is_float(var)
is_int Find whether the type of a variable is integer bool is_int(var)
is_nan Finds whether a value is not a number bool is_nan(var)
is_null Finds whether a variable is NULL bool is_null(var)
is_numeric Finds whether a variable is a number or a numeric string bool is_numeric(var)
is_string Find whether the type of a variable is string bool is_string(var)
join (New in 2.0 build 130129) Join elements as a new string join(arg1, arg2, ... argN)
list Return comma-separated list of non-blank values string list(arg1, arg2, ... argN)
log The logarithm of number to base, if given, or the natural logarithm. number log(number,base=e)
ltrim Strip whitespace (or other characters) from the beginning of a string string ltrim(string [, charlist])
max Find highest value number max(arg1, arg2, ... argN)
min Find lowest value number min(arg1, arg2, ... argN)
mktime Get UNIX timestamp for a date (each of the 6 arguments are optional) number mktime([hour [, minute [, second [, month [, day [, year ]]]]]])
modulo-function The modulo function is not supported yet. You can use the floor() function instead floor(x/y)==(x/y)
nl2br Inserts HTML line breaks before all newlines in a string string nl2br(string)
number_format Format a number with grouped thousands string number_format(number)
pi Get value of pi number pi()
pow Exponential expression number pow(base, exp)
quoted_printable_decode Convert a quoted-printable string to an 8 bit string string quoted_printable_decode(string)
quoted_printable_encode Convert a 8 bit string to a quoted-printable string string quoted_printable_encode(string)
quotemeta Quote meta characters string quotemeta(string)
rand Generate a random integer, see this example int rand() OR int rand(min, max)
regexMatch compare a string to a regular expression bool regexMatch(pattern,input)
round Rounds a number to an optional precision number round(val [, precision])
rtrim Strip whitespace (or other characters) from the end of a string string rtrim(string [, charlist])
sin Sine number sin(arg)
sprintf Return a formatted string string sprintf(format, arg1, arg2, ... argN)
sqrt Square root number sqrt(arg)
stddev Calculate the Sample Standard Deviation for the list of numbers number stddev(arg1, arg2, ... argN)
str_pad Pad a string to a certain length with another string string str_pad(input, pad_length [, pad_string])
str_repeat Repeat a string string str_repeat(input, multiplier)
str_replace Replace all occurrences of the search string with the replacement string string str_replace(search, replace, subject)
strcasecmp Binary safe case-insensitive string comparison int strcasecmp(str1, str2)
strcmp Binary safe string comparison int strcmp(str1, str2)
strip_tags Strip HTML and PHP tags from a string string strip_tags(str, allowable_tags)
stripos Find position of first occurrence of a case-insensitive unicode string (starting by 0, return false if not found) int stripos(haystack, needle [, offset=0])
stripslashes Un-quotes a quoted string string stripslashes(string)
stristr Case-insensitive strstr string stristr(haystack, needle [, before_needle=false])
strlen Get string length int strlen(string)
strpos Find position of first occurrence of an unicode string (starting by 0, return false if not found) int strpos(haystack, needle [ offset=0])
strrev Reverse a string string strrev(string)
strstr Find first occurrence of a string string strstr(haystack, needle[, before_needle=false])
strtolower Make a string lowercase string strtolower(string)
strtotime Parse about any English textual datetime description into a Unix timestamp int strtotime(string)
strtoupper Make a string uppercase string strtoupper(string)
substr Return part of an unicode string string substr(string, start [, length])
sum Calculate the sum of values in an array number sum(arg1, arg2, ... argN)
sumifop Sum the values of answered questions in the list which pass the criteria (arg op value) number sumifop(op, value, arg1, arg2, ... argN)
tan Tangent number tan(arg)
time Return current UNIX timestamp number time()
trim Strip whitespace (or other characters) from the beginning and end of a string string trim(string [, charlist])
ucwords Uppercase the first character of each word in a string string ucwords(string)
unique Returns true if all non-empty responses are unique boolean unique(arg1, ..., argN)


計画されている(または検討中の)関数の詳細を知りたい場合は、ここをクリックしてください。


式マネージャーとローカル変数

ページのJavaScriptを適切に構築するため、式マネージャーはページに設定されている変数とJavaScript IDが何であるかを知る必要があります(例: document.getElementById(x))。また、他のページにどの変数が設定されているかも知る必要があります(これにより、必要な<input type='hidden' value='x'>フィールドが存在しているか確認できます)。


条件の入れ子

いずれかの変数がfalseである場合、式全体はfalseになります。たとえば、次の表では、N/Aは変数の1つがtrueでないことを意味します。


Operator Example a b Result
+ (unary) +a N/A false
! !a N/A false
== (or eq) a == b N/A 5 false
== (or eq) a == b N/A 0 false
== (or eq) a == b N/A N/A false
!= (or ne) a != b N/A 5 false
!= (or ne) a != b N/A N/A false
!= (or ne) a != b N/A 0 false
> (or gt) a > b N/A 5 false
>= (or ge) a >= b N/A 5 false
< (or lt) a < b N/A 5 false
<= (or le) a <= b N/A 5 false
and a and b N/A 5 false
and a and b N/A N/A false
or a or b N/A N/A false
or a or b N/A 5 false
+ a + b N/A 5 false
* a * b N/A 5 false
/ a / b 5 N/A false
() (a) N/A false
(exp) (a && b) N/A 5 false
(exp) op (exp) (b + b) > (a && b) N/A 5 false
function sum(a,b,b) N/A 5 false
function max(a,b) N/A 5 false
function min(a,b) N/A 5 false
function implode(', ',a,b,a,b) N/A 5 false
function if(a,a,b) N/A 5 false
function is_empty(a) N/A false
function is_empty(a) 0 (or blank) true
function !is_empty(a) N/A false


入れ子条件の上書き

出現条件を満たした回答の合計を表示したいとします。式 {sum(q1,q2,q3,...,qN)}を使おうとするでしょう。しかし、これは内部的にLEMif(LEManyNA("q1","q2","q3",...,"qN"),"",sum(LEMval("q1"),LEMval("q2"),LEMval("q3"),...,LEMval("qN")))に変換されます。これにより、値q1〜qNのいずれかが出現条件を満たさない場合、式は常にfalseを返します。この場合、sum()はすべての質問が出現して回答されない限り"0"となります。

To get around this, each variable can have a ".NAOK" suffix (meaning that Not Applicable is OK) added to it. In such cases, the following behavior occurs. Say you have a variable q1.NAOK:

  1. q1 is not added to the LEManyNA() clause
  2. LEMval('q1') will continue to check whether the response is relevant and will return "" if it is not (so individual irrelevant responses will be ignored, but they will not void the entire expression).

したがって、合計を求める方法は、次の式となります。sum(q1.NAOK,q2.NAOK,q3.NAOK,...,qN.NAOK)

The use of the .NAOK suffix also lets authors design surveys that have several possible paths but then converge on common paths later. For example, say subjects answer a survey in a way that is outside the normal range of responses. The author could alert the subjects that they may not get valid results, and ask them whether they really want to continue with the survey. If they say "Yes", then the rest of the questions will be shown. The condition for the "rest of the questions" would check whether the initial responses were answered within the normal range OR whether the subject said "Yes" to the question that is only relevant if they answered outside the normal range.


式マネージャーはどのように条件付き文言調整を実現するか?

ここでは、カスタマイズ(質問タイプ'expr'は式を意味します)の例を示します。


Question Code Relevance Question Type Question
name 1 text What is your name?
age 1 text How old are you?
badage !is_empty(age) expr {(age<16) or (age>80)}
agestop badage message Sorry, {name}, you are too {if( (age<16),'young',if( (age>80),'old','middle-aged') ) } for this test.
kids !badage yesno Do you have children?
parents 1 expr {!badage && kids=='Y'}
numKids parents text How many children do you have?
kid1 parents && numKids >= 1 text How old is your first child?
kid2 parents && numKids >= 2 text How old is your second child?
kid3 parents && numKids >= 3 text How old is your third child?
kid4 parents && numKids >= 4 text How old is your fourth child?
kid5 parents && numKids >= 5 text How old is your fifth child?
sumage 1 expr {sum(kid1.NAOK,kid2.NAOK,kid3.NAOK,kid4.NAOK,kid5.NAOK)}
report parents text {name}, you said you are {age} and that you have {numKids}.  The sum of ages of your first {min(numKids,5)} kids is {sumage}


このアンケート例をダウンロードするには、次のリンクをクリックしてください。子供の数のアンケート例

これらの質問はすべて1つのページ(たとえば同じグループ)に入れることができ、出現条件に合致する質問のみが表示されます。さらに、子供の年齢を入力すると、最後の質問のsum()式がページ上で動的に更新されます。

式マネージャーは、各式を名前付き<span>要素で囲むことでこの機能を提供します。値が変更されるたびに、その<span>要素に表示される式を再計算し、再表示します。そのようなカスタマイズされた式が同じページに数十、または数百もあっても、ページは一度の画面更新ですべて再表示されます。


構文ハイライト

式の入力と検証を支援するために、EMでは以下のような構文強調表示機能を提供しています。

構文ハイライトの種類と意味

Color Sample Meaning Tooltip Comments
tan background Sample the whole equation none Anything within curly braces that is recognized as an equation (e.g., there is no leading or trailing whitepace) will be color-coded with a tan background to help distinguish it from surrounding text
bold red text Sample An error Some explanation on error Can be an unknow variable or an error in function. Survey is broken and the questions that rely on the respective expression will not be shown to the respondents.
blue text Sample function name meaning and allowable syntax It refers to function names or things that should be functions since they are followed by an open parenthesis. They are displayed in bold blue text. Tooltips show the meaning and allowable syntax for the function.
grey text Sample string none Single and double-quoted strings are shown in grey text.
cyan text Sample variable set on the same page, [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on the same page as the question you are currently editing is shown in cyan text (it can be updated in javascript). The tooltip shows its name (if you used INSERTANS:xxx) or its SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is shown.
green text Sample variable set on a prior page [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a prior page is shown in bold green text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is shown.
bold pink text Sample variable set on a later page in general : empty at survey start, but can be filled with index or move previous [name or SGQA code]: question; value; answerList showing codes for each value Any variable that is set on a prior page is shown in bold pink text. The tooltip shows its name (if you used INSERTANS:xxx) or SGQA code (if you used the new naming system), the actual question, and its current value (or blank if not set). If the question type expects responses from an enumerated value set, the mapping of the codes to display values is show.
bold tan text Sample a lime replacement value the value Lime Replacement Strings (like {TOKEN:xxx}, {PRIVACY_MESSAGE}) are shown in bold tan text.
red text Sample assignment operator (=) warning message If you use one of the assignment operator (=), that operator will be displayed in red text. This is meant to help prevent accidental re-assignment of values when you really meant to check whether a == b instead of setting the value of a = b.
normal black text Sample punctuation none All other punctuation signs within the expression are shown as normal black text.
red-boxed text a bold red line surrounds the error syntax error description of the error Any detected syntax errors are shown within red boxes. The tooltip shows the error. Examples include unmatched parentheses, use of undefined functions, passing the wrong number of arguments to functions, poorly structured expressions (e.g., missing operators between variables), trying to assign a new value to a read-only variable, trying to assign values to non-variables, or using unsupported syntax. Note that the syntax error dectection system may only report one error in an expression even if there are multiple errors; however, if any errors are detected, at least one error will be shown.


ツールチップとは、特定の関数や変数にカーソルを置いたときに表示されるポップアップメッセージのことです。

参考記事

式マネージャーのサンプル

ユースケースとHowTo

ステップバイステップの例

開発者向け参考情報

ロードマップ/状況/ToDoリスト