<?php
/*
  HISTORY:
    v0.72 (by ftruscot)
	- Bugfix: in doTemplateVar, field name not retrieved from blogOption correctly when using otherblog skinvar
    v0.71 (by eph)
      !! Database incompatible with previous versions !!
      - More than 5 custom fields, 3 by default (see install instructions)
      - Multiline fields (Blog Settings)
      - Field names are set per blog (Blog Settings)
      - Mixed CustomField strings possible, i.e.:
        <%CustomField(<a href="$URL" title="$Name">$Name</a>)%>
      - I18N internationalization support
      - Bugfix: Double posting bug fixed
      - Bugfix: Fields show up in index page too
      - Further discussion at http://forum.nucleuscms.org/viewtopic.php?t=8684
    v0.64 (by Felix)
      - <%CustomField(<b>Mood:</b> $mood)%> outputs "Mood: happy" or ""
      - <b>Mood:</b> <%CustomField($mood)%> outputs "Mood: happy" or "Mood: " .. 
    v0.61/0.62/0.63
      - Code improvements as suggested by karma/Gen
    v0.6 (by Roel)
      - applied fixes from forum thread: http://forum.nucleuscms.org/viewtopic.php?t=1033
      - Added custom fields for older items
      - Added Cleanup upon uninstall option
      - Added supportsFeature
    v0.5
      - Original release
 
 
  INSTALLATION:
      - After downloading the file, check it for any whitespace before the
        beginning and after the end of the plugin code (because that can f*** up
        the scripts,  so remove that if you find any).
      - Change the number of custom fields in function NP_CustomField(),
        if you want to have more or less than 3 fields.
      - Upload it to your plugins dir yoursite.com/nucleus/plugins
      - In the admin area, go to the Plugin page and install the plugin
      - In the Blog settings edit the plugin options:
          a) give the fields a name to enable them,
          b) save options.
      - Go to the Template Overview, selected 'detailed' (or whatever the name
        of the template for your detailed/item pages is), and add
        <%CustomField($fieldnumber)%> or <%CustomField($fieldname)%> 
        to the Item Body template-part, and save.
        Fieldnames are case-sensitive!
*/
 
// plugin needs to work on Nucleus versions <=2.0 as well
if (!function_exists('sql_table'))
{
   function sql_table($name) {
      return 'nucleus_' . $name;
   }
}
 
class NP_CustomField extends NucleusPlugin {
   // name of plugin
 
   function NP_CustomField() {
      // number of custom fields
      $this->n = 3;
 
      // available languages
      $available = array('english','german');
      $this->language = getLanguageName();
      if (!in_array($this->language,$available)) {
         $this->language = 'english';
      }
   }
 
   function I18N($key) {
      $lng['description']['english'] = 'Allows you to add extra fields to the add item form';
      $lng['cf_title']['english']    = "Custom fields";   // Just the title displayed on top of forms and the like
      $lng['cfname_1']['english']    = "Custom field ";      // same for _1 and _2 here
      $lng['cfname_2']['english']    = " name?";         // that's number _2, this one, yes.
      $lng['cfmultiline']['english'] = "Multiline custom fields?";  
      $lng['cleanup_description']['english'] = "Remove customfield data from table when uninstalling plugin?";
 
      $lng['description']['german']  = 'Allows you to add extra fields to the add item form';
      $lng['cf_title']['german']     = "Weitere Angaben";
      $lng['cfname_1']['german']     = "Name des Angabefelds Nr. ";
      $lng['cfname_2']['german']     = "?";
      $lng['cfmultiline']['german']  = "Multiline Weitere Angaben?";
      $lng['cleanup_description']['german'] = 
        "Gespeicherte Inhalte der zusätzlichen Angabefenster bei der Plugindeinstallation löschen?";
 
      return $lng[$key][$this->language];
   }
 
   function getName() {
      return 'Custom Field';
   }
 
   // author of plugin
   function getAuthor()  {
      return 'Tim Broddin & others';
   }
 
   // an URL to the plugin website
   // can also be of the form mailto:foo@bar.com
   function getURL()
   {
      return 'http://www.fuckhedz.com/';
   }
 
   // version of the plugin
   function getVersion() {
      return '0.72';
   }
 
   // a description to be shown on the installed plugins listing
   function getDescription() {
      return $this->I18N('description');
   }
 
   function supportsFeature($what) {
      switch($what) {
        case 'SqlTablePrefix':
          return 1;
        default:
          return 0;
      }
   }
 
   function install() {
      // Create database, copycated the IF NOT EXISTS from NP_Trackback ;)
      sql_query('CREATE TABLE IF NOT EXISTS ' . sql_table('plug_customfield') . ' (id INT(9) NOT NULL AUTO_INCREMENT PRIMARY KEY , itemid INT(9) NOT NULL , field INT(2) NOT NULL , value TEXT NOT NULL, ctrl BOOL NOT NULL)');
 
      // Give names to custom fields
      // Loop n times
      for ($i=1;$i<=$this->n;$i++) {
         $this->createBlogOption('f'.$i.'name',$this->I18N('cfname_1').$i.$this->I18N('cfname_2'),'text','');
      }
      $this->createBlogOption('fmultiline',$this->I18N('cfmultiline'),'yesno','no');
 
      // Uninstall option (copied from np_views)
      $this->createOption('Cleanup',$this->I18N('cleanup_description'),'yesno','no');
   }
 
   function unInstall() {
      if ($this->getOption('Cleanup') == 'yes')
        mysql_query('DROP TABLE ' . sql_table('plug_customfield'));
   }
 
   function getEventList() {
      return array('PostAddItem','PreUpdateItem','AddItemFormExtras', 'EditItemFormExtras', 'PostDeleteItem');
   }
 
   function getTableList() {
     return sql_table('plug_customfield');
   }
 
   function event_AddItemFormExtras($data) {
      global $manager;
      // Found no function to detect blogid in this time -> do the long way
      if (is_array($manager->blogs)) {
          $tmp_keys = array_keys($manager->blogs);
          $blogid = $tmp_keys[0];
      }      
 
      // Print the title
      echo '<h3>'.$this->I18N('cf_title').'</h3>';
      echo '<table border="0">';
 
     // Loop n times
      for ($i=1;$i<=$this->n;$i++) {
         // If option is enabled print the field
         $name = $this->getBlogOption($blogid,'f' . $i . 'name');
         if (str_replace(' ', '', $name) != '') {
            echo '<tr>';
            echo '<td><label for="plug_cf_f' . $i . '">' . $name . ': </label></td>';
            if ($this->getBlogOption($blogid,'fmultiline')=='yes') {
              echo '<td><textarea value="" id="plug_cf_f' . $i . '" name="plug_cf_f' . $i . '" cols="80" rows="5"></textarea></td>';
            } else {
              echo '<td><input type="text" value="" id="plug_cf_f' . $i . '" name="plug_cf_f' . $i . '" size="64" maxlength="255" /></td>';
            }
            echo '</tr>';            
         }
       }
      echo '</table>';
   }
 
   function event_EditItemFormExtras($data) {
      global $manager;
      // Found no function to detect blogid in this time -> do the long way
      if (is_array($manager->blogs)) {
          $tmp_keys = array_keys($manager->blogs);
          $blogid = $tmp_keys[0];
      }      
 
      // Print the title
      echo '<h3>'.$this->I18N('cf_title').'</h3>';
      echo '<table border="0">';
 
     // Loop n times
      for ($i=1;$i<=$this->n;$i++) {
         // If option is enabled print the field
         $name = $this->getBlogOption($blogid, 'f' . $i . 'name');
         if (str_replace(' ', '', $name) != '') {
 
            // Query for the contents of the field
            $itemid = $data['variables']['itemid'];   
            $itemid_escaped = intval($itemid);
            $query = "SELECT value FROM " . sql_table('plug_customfield') . " WHERE itemid='$itemid_escaped' AND field='$i'";
            $result = mysql_query($query);
            $num = mysql_num_rows($result);
 
            // Are there any matches?
            // If the field doesn't exist for this item, create it
            if ($num == 0) {
               $contents = "";
 
               $itemid_escaped = intval($itemid);
               $query = "INSERT INTO " .sql_table('plug_customfield'). "(id,itemid,field,value,ctrl) VALUES('','$itemid_escaped','$i','',0);";
               mysql_query($query);
 
            } else {
               $contents = mysql_result($result,0,'value');
            }
 
            // Print the field
            echo '<tr>';
            echo '<td><label for="plug_cf_f' . $i . '">' . $name . ': </label></td>';
            if ($this->getBlogOption($blogid,'fmultiline')=='yes') {
              echo '<td><textarea value="" id="plug_cf_f' . $i . '" name="plug_cf_f' . $i . '" cols="80" rows="5">' , htmlspecialchars($contents) , '</textarea></td>';
            } else {
              echo '<td><input type="text" value="' , htmlspecialchars($contents) , '" id="plug_cf_f' . $i . '" name="plug_cf_f' . $i . '" size="64"  maxlength="255" /></td>';
            }
            echo '</tr>';            
         }
      }
      echo '</table>';
   }
 
   function event_PostAddItem($data) {
      global $manager;
      // Found no function to detect blogid in this time -> do the long way
      if (is_array($manager->blogs)) {
          $tmp_keys = array_keys($manager->blogs);
          $blogid = $tmp_keys[0];
      }      
 
     // Loop n times
      for ($i=1;$i<=$this->n;$i++) {
         // If option is enabled print the field
         $name = $this->getBlogOption($blogid, 'f' . $i . 'name');
         if (str_replace(' ', '', $name) != '') {
 
            $value = requestVar('plug_cf_f' . $i);
            $itemid = $data['itemid'];
            $value_escaped = addslashes($value);
            $itemid_escaped = intval($itemid);
            $query = "INSERT INTO " . sql_table('plug_customfield') . " (id,itemid,field,value,ctrl) VALUES('','$itemid_escaped','$i','$value_escaped',0);";
            mysql_query($query);
         }
      }
   }
 
   function event_PreUpdateItem($data) {
      global $manager;
      // Found no function to detect blogid in this time -> do the long way
      if (is_array($manager->blogs)) {
          $tmp_keys = array_keys($manager->blogs);
          $blogid = $tmp_keys[0];
      }      
 
     // Loop n times
      for ($i=1;$i<=$this->n;$i++) {
         // If option is enabled print the field
         $name = $this->getBlogOption($blogid, 'f' . $i . 'name');
         if (str_replace(' ', '', $name) != '') {
 
            $value = requestVar('plug_cf_f' . $i);
            $itemid = $data['itemid'];
            $value_escaped = addslashes($value);
            $itemid_escaped = intval($itemid);
            $query = "UPDATE " . sql_table('plug_customfield') . " SET value='$value_escaped', ctrl=NOT ctrl WHERE itemid='$itemid_escaped' AND field='$i'";
            if(mysql_query($query)) {
               if (mysql_affected_rows() == 0) {
                  $query = "INSERT INTO " . sql_table('plug_customfield') . " (id,itemid,field,value,ctrl) VALUES('','$itemid_escaped','$i','$value_escaped',0);";
                  mysql_query($query);
               }
            }
         }
      }
   }
 
   function event_PostDeleteItem($data) {
      $itemid = $data['itemid'];
      $itemid_escaped = intval($itemid);
      $query = "DELETE FROM " . sql_table('plug_customfield') . " WHERE itemid='$itemid_escaped'";
      mysql_query($query);
   }
 
   function doTemplateVar(&$item, $mask) {
      //global $blog;
      //$blogid = $blog->blogid;
 
      // $mask suits param1's function better than $mask.
 
      $itemid = $item->itemid;
      $itemid_escaped = intval($itemid);
 
	  $blogid = getBlogIDFromItemID(intval($itemid));
 
      // We havent got any "field" to search by any more, $mask now contains "<b>$mood</b>" or the like.
      $query = "SELECT field,value FROM " . sql_table('plug_customfield') . " WHERE itemid='$itemid_escaped'";
      $result = mysql_query($query);
 
      $i = 0;
      while($row = mysql_fetch_array($result)) {
        $cf    = $row["field"];
        $cfval = $row["value"];  // e. g. = "sad";
        $cfname= $this->getBlogOption($blogid, 'f' . $cf . 'name');  // e. g. = "mood";
        if($cfval!="") {
           $search[$i]   = '$'.$cf;
           $search[$i+1] = '$'.$cfname;
           $replace[$i]  = $cfval;
           $replace[$i+1]= $cfval;
        } else {
           $search2[$i]   = '$'.$cf;
           $search2[$i+1] = '$'.$cfname;
           $replace2[$i]  = $cfval;
           $replace2[$i+1]= $cfval;
        }
        $i = $i+2;
      }
 
      $return = str_replace($search, $replace, $mask);   // replace $1 and $mood by $fields["mood"] etc.
      // If there hasnt been any replacement, it wont echo anything at all.
      if($return != $mask) {
        $return2 = str_replace($search2, $replace2, $return);   // replace $1 and $mood by empty fields
        echo $return2;
      }
   }
}
?>
np_customfield_code.txt · Last modified: 2011/05/12 20:10 (external edit)
 
Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Noncommercial-Share Alike 3.0 Unported
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki