Revision [15809]

This is an old revision of StructDataAction made by DomBonj on 2006-12-16 14:02:12.

 

StructData Action

See also:
works with:
  • Wikka 1.1.6.2
NOT Included in any Wikka version
Last edited by DomBonj:
v0.98: i18n, vCard export, column order in ItemTable
Sat, 16 Dec 2006 14:02 UTC [diff]

This is the development page for the structdata action.

Installation


Code

<?php
#
# Defines, optionnally displays a structured data item or
# displays the results of a selection request
#
# @package      Actions
# @name         structdata
#
# @authors      DomBonj
# @version      0.98
# @input        Parameters =  (type='mytype' data='datalist' [print=('basic'|'table'|'list'|'false')]
#               | req='reqid' [help][p1='val1'][p2='val2"][p3='val3'])
#               $datalist: list of 'pname'='pval' parameters, separated by spaces.
#                 restrictions: pval shall not include a ' followed by a space
#               $reqid : the name of a predefined request
#               $val1, $val2, $val3 : optional parameters for request $reqid
#               $help, if present, displays a one-line help for request $reqid
#
# @uses         Wakka::ReturnSafeHtml()
# @uses         Wakka::LoadAll()
# @uses         Wakka::GetPageTag()
# @uses         Wakka::href()
#
# @notes        Add your code into the flagged areas
#

if (!defined('ERROR_PARAMETER_MANDATORY')) define ('ERROR_PARAMETER_MANDATORY', "The '%s' parameter is mandatory");
if (!defined('ERROR_INCORRECT_DATE_FORMAT')) define ('ERROR_INCORRECT_DATE_FORMAT', "Incorrect format for '%s' parameter: use 'yyyy-mm-dd'");

if (!function_exists('SDerror'))
{
  function SDerror($msg) {
    return ("<em class='error'>$msg</em><br />");
  }

  function SDhandleitem($type, $params, $printmode) {
    $table_css = "class='wikka' cellpadding='2' cellspacing='1' border='2'";
    $myerr = '';
    extract($params);
        $mystr="";
        switch ($type) {
        // custom formatting, data validation and hyperlink addition
          case 'ToDo':
            if (!$owner) $myerr .= SDerror(sprintf(ERROR_PARAMETER_MANDATORY, 'owner'));
            if (!$desc) $myerr .= SDerror(sprintf(ERROR_PARAMETER_MANDATORY, 'desc'));
            preg_match('/(\d+)[\-\/](\d+)[\-\/](\d+)/', $date_open, $ymd);
            if (!checkdate($ymd[2], $ymd[3], $ymd[1]))
              $myerr .= SDerror(sprintf(ERROR_INCORRECT_DATE_FORMAT, 'date_open'));
            preg_match('/(\d+)[\-\/](\d+)[\-\/](\d+)/', $date_due, $ymd2);
            if (!checkdate($ymd2[2], $ymd2[3], $ymd2[1]))
              $myerr .= SDerror(sprintf(ERROR_INCORRECT_DATE_FORMAT, 'date_due'));
          break;

          case 'Card':
            if (!$n) {
              $myerr.= SDerror(sprintf(ERROR_PARAMETER_MANDATORY, 'n'));
            }
            $n_array = split(';', $n);
            $name = (isset($n_array[1]) ? (ucwords(strtolower($n_array[1]))." ") : "").ucwords(strtolower($n_array[0]));
            $tooltip = isset($tel) ? "phone: $tel" : "";
            $tooltip .= (isset($fax) ? ($tooltip ? " / fax: $fax" : "fax: $fax") : "");
            $mystr = "<a href='mailto:$email' title='$tooltip'>".$name."</a>". ($org != '' ? " ($org)" : "");
          break;

/*------------------------------- begin customization area -----------------------------
          case 'mydataitem':
            <my validation and hyperlinking code>
            $mystr = <my formatting>;
          break;
--------------------------------- end customization area -----------------------------*/

        }

        if (!$mystr) {
        // type did not match any custom type : fallback to a standard type
          switch ($printmode) {
            case 'table':
              $mystr = "<table $table_css>"; $r1="<tr>"; $r2="<tr>";
              foreach ($params as $name => $value) {
                if ($name != 'print') {
                  $r1 .= "<th class='comment'>$name</th>";
                  $r2 .= "<td>$value</td>";
                }
              }
              $mystr .= "$r1</tr>$r2</tr></table>";
            break;

            case 'list':
              $mystr = "<table $table_css><tr class='comment'><th>name</th><th>value</th></tr>";
              foreach ($params as $name => $value) {
                if ($name != 'print') {
                  $mystr .= "<tr><td class='comment' align='right'>$name</td><td>$value</td></tr>";
                }
              }
              $mystr .= "</table>";
            break;

            case 'basic':
            default:
              $mainparam = (isset($value) ? $value : (isset($id) ? $id : (isset($name) ? $name : '')));
//              $mystr="<kbd class='keys'>StructuredData</kbd><span>&nbsp;&nbsp;type='{$type}'&nbsp;&nbsp;value/id='$mainparam'</span>";
              $mystr="<span title='structured data item: $type' class='notes'>{$type}".(isset($mainparam)?"&nbsp;[$mainparam]":"")."</span>";
            break;
          }
        }

        if ($myerr) {
          return ($myerr);
        } else if ($printmode != 'false') {
          // display the data item
          return ($mystr);
        }
  }

  function SDbuildvcard($row) {
      $n_array = split(';', $row['n']);
      $name = (isset($n_array[3])? $n_array[3]." " : "").(isset($n_array[1]) ? (ucwords(strtolower($n_array[1]))." "):"").(isset($n_array[2])? $n_array[2]." ": "").ucwords(strtolower($n_array[0])).(isset($n_array[4])? ", ".$n_array[4]: "");
      $str = "BEGIN:VCARD\r\nVERSION:2.1\r\nN:{$row['n']}\r\nFN:$name\r\n";
      $str .= $row['org'] ? "ORG:{$row['org']}\r\n" : "";
      $str .= $row['tel'] ? "TEL;WORK:{$row['tel']}\r\n" : ""; // by default, tel is shown as work phone
      $str .= $row['fax'] ? "TEL;FAX:{$row['fax']}\r\n" : "";
      $str .= $row['email'] ? "EMAIL;INTERNET:{$row['email']}\r\n" : "";
      $str .= "END:VCARD\r\n";
      return ($str);
  }

  function SDrunreq ($this, $reqid, $rows, $p1=null, $p2=null, $p3=null) {
  // $rows array row format: ('_wikkapage' => <page tag>, 'field1' => <val1>, 'field2' => <val2>, ...)
    $table_css = "class='wikka' cellpadding='2' cellspacing='1' border='2'";
    switch($reqid) {
      case 'ItemTable':  // p1 = type of dataitem, p2 = column order list
          $i = 0;
          $keyorder = array();
          if ($p2) {
              $mycols = split(',', $p2);
              foreach ($mycols as $lacol)
                  $keyorder[$lacol] = $i++;
          }
          $mystr0 = "<table $table_css><tr class='comment'>";
          foreach ($rows as $row) {
              if (($row['_wikkapage']==$this->GetPageTag()) && ($row['type']==$p1)) {
                  $tmp_tr = array();
                  $mystr .= "<tr>";
                  foreach ($row as $key => $val) {
                      if (($key != '_wikkapage') && ($key != 'type') && ($key != 'print') && !isset($keyorder[$key])) {
                          $keyorder[$key] = $i++;
                      }
                      if (($key != '_wikkapage') && ($key != 'type') && ($key != 'print')) {
                          $tmp_tr[$keyorder[$key]] = $val;
                      }
                  }
                  for ($j=0; $j < $i; $j++) {
                      $mystr .= "<td>".$tmp_tr[$j]."</td>";
                  }
                  $mystr .= "</tr>";
              }
          }
          // build table header row
          $tmp_tr = array();
          foreach ($keyorder as $param => $k) {
              $tmp_tr[$k] = $param;
          }
          for ($j=0; $j < $i; $j++) {
              $mystr0 .= "<th>".$tmp_tr[$j]."</th>";
          }
          $mystr = $mystr0. "</tr>". $mystr. "</table>";
          if (!$i) $mystr='';   // empty table: display nothing
      break;

      case 'ToDos':  // p1 = this owner only;  p2 = this status only
          $mydata=array();
          $i=0;
          foreach ($rows as $row) {
              if ($row['type']=='ToDo') {
                  if ( (!$p1 || ($p1 == $row['owner'])) && (!$p2 || ($p2 == $row['status'])) ) {
                      // Transform all dates into a common format for sorting purposes
                      $mydata[date("Y-m-d", strtotime($row['date_open']))."_".$i++] = "<tr><td>{$row['owner']}</td><td>{$row['desc']}</td>".
                        "<td".((strtotime($row['date_due'])<time())?" style='background-color:red; color:white; '":"").">{$row['date_due']}</td>".
                        "<td align='center'><a href='{$_SERVER['PHP_SELF']}?wakka={$row['_wikkapage']}'>{$row['_wikkapage']}</a></td></tr>";
                  }
              }
          }
          krsort($mydata);
          $mystr = "<table $table_css><tr class='comment'><th>owner</th><th>description</th><th>due date</th><th>page link</th></tr>";
          foreach ($mydata as $key => $val) {
              $mystr .= "$val";
          }
          $mystr .= "</table>";
      break;

      case 'Cards':  // p1 = this org only;  p2 = sort key ; p3 = format (vCard or default)
          $mydata=array();
          $i=0;
          foreach ($rows as $row) {
              if ($row['type']=='Card') {
                  if ( (!$p1 || ($p1 == $row['org'])) ) {
                      $sortkey = strtolower((isset($p2) && $p2) ? $row[$p2] : (isset($row['n']) ? $row['n'] : $i))."__".$i++;
                      $n_array = split(';', $row['n']);
                      $mydata[$sortkey] = "<tr><td>{$n_array[0]}</td><td>{$n_array[1]}</td>".
                        "<td>{$row['email']}</td><td>{$row['tel']}</td><td>{$row['fax']}</td>".(isset($p2) ? "<td>{$row['org']}</td>":"")."</tr>";
                      $myvcards[$sortkey] = SDbuildvcard($row);
                  }
              }
          }
          if ($p3 == 'vCard') {
              $mystr="";
              $cnt=0;
              ksort ($myvcards);
              foreach ($myvcards as $key => $card) {
                  $mystr .= "$card\r\n";
                  $cnt++;
              }
              $mystr ='<form action="'.$this->href().'/grabcode" method="post" id="form_vCard" class="grabcode">
              <input type="submit" name="save" class="grabcodebutton" style="line-height:10px; float:left; vertical-align: middle; margin-right:20px; margin-top:0px; font-size: 10px; color: #000; font-weight: normal; font-family: Verdana, Arial, sans-serif; background-color: #DDD; text-decoration: none; height:18px;" value="Grab '
.$cnt.($cnt>1?' vCards':' vCard').'" title="Download vCard file" />
              <input type="hidden" name="code" value="'
.$mystr.'" /><input type="hidden" name="filename" value="wikka_vcards" /></form>';
          } else { // default (table) format
              ksort($mydata);
              $mystr = "<table $table_css><tr class='comment'><th>Last name</th><th>Given name</th><th>Email</th><th>Phone</th><th>Fax</th>".(isset($p2) ? "<th>Organization</th>":"")."</tr>";
              foreach ($mydata as $key => $val) {
                  $mystr .= "$val";
                  }
              $mystr .= "</table>";
          }
      break;

/*------------------------------- begin customization area -----------------------------
      case 'myreq':
          <mycode>
          $mystr = <what I want to print>
      break;
--------------------------------- end customization area -----------------------------*/

    }
    return ($mystr);
  }

  function SDdohelp ($reqid) {
    $helpstr = '';
    switch($reqid) {
        case 'ItemTable':
            $helpstr = "$reqid p1=<i>type</i> [p2=<i>column order list</i>] ";
        break;

        case 'ToDos':
            $helpstr = "$reqid [p1=<i>owner</i>] [p2=<i>status</i>] ";
        break;

        case 'Cards':
            $helpstr = "$reqid [p1=<i>org filter</i>] [p2=<i>sort column name</i>] [p3=<i>format (vCard|table)</i>] ";
        break;

/*------------------------------- begin customization area -----------------------------
      case 'myreq':
        $helpstr = 'myfoobar';
      break;
--------------------------------- end customization area -----------------------------*/

    }
    return ($helpstr);
  }
}

if ((!isset($type) || !$type) && (!isset($req) || !$req) && !isset($help)) {
    $output = SDerror("Usage: structdata type='<i>mytype</i>' [print='<i>printmode</i>'] data=\"[more parameters]\"");
}
else if (isset($help))
{ // display one-line help for $req
    $output = SDdohelp ($req);
}
else if (isset($req))
{ // this is a request: load all relevant data in an associative array: $myrows
    $query = "SELECT body, tag FROM ".$this->config['table_prefix']."pages WHERE ((latest = 'Y') AND (body LIKE '%{{structdata%'))";
    $rows = $this->LoadAll($query);
    foreach ($rows as $row) {
        if (preg_match_all('/\{\{structdata(.+?)\}\}/', $row['body'], $matches)) {
            foreach ($matches[1] as $mym) {
                $newrow=array('_wikkapage' => $row['tag']);
                if (preg_match('/type=\"(.*?)\"[ \t]*.*?data=\"(.*?)\"/', $mym, $matches2)) {
                    $newrow['type'] = $matches2[1];
                    preg_match_all('/(\w+?)\=\'(.*?)\'/', $matches2[2], $matches3);
                } else if (preg_match('/data=\"(.*?)\"[ \t]*.*?type=\"(.*?)\"/', $mym, $matches2)) {
                    $newrow['type'] = $matches2[2];
                    preg_match_all('/(\w+?)\=\'(.*?)\'/', $matches2[1], $matches3);
                }
                for ($i=0; $i < count($matches3[1]); $i++) {
                    $newrow[strtolower($matches3[1][$i])] = $matches3[2][$i];
                }
                $myrows[] = $newrow;
            }
        }
    }
   // we run the request
   $output = SDrunreq ($this, $req, $myrows, (isset($p1)?$p1:''), (isset($p2)?$p2:''), (isset($p3)?$p3:''));
}
else
{ // this is a data item : process it
    if ($data) {
        preg_match_all('/(\w*)\=\'(.*?)\'\s*?/', $data, $matches);
        for ($i=0; $i<count($matches[1]); $i++) {
        // parameter name is case-insensitive
            $params[strtolower($matches[1][$i])] = $matches[2][$i];
        }
        $output = SDhandleitem ($type, $params, isset($print)?$print:'');
    } else {
        $output = SDerror (sprintf(ERROR_PARAMETER_MANDATORY, 'data'));
    }
}

if ($output) { // print the result
    $output = $this->ReturnSafeHTML($output);
    echo $output;
}
?>



CategoryUserContributions
Valid XHTML :: Valid CSS: :: Powered by WikkaWiki