Alpha Framework alpha--model
[ class tree: alpha--model ] [ index: alpha--model ] [ all elements ]

Source for file TagObject.inc

Documentation is available at TagObject.inc

  1. <?php
  2.  
  3. require_once $config->get('sysRoot').'alpha/model/AlphaDAO.inc';
  4. require_once $config->get('sysRoot').'alpha/util/helpers/AlphaValidator.inc';
  5.  
  6. /**
  7.  *
  8.  * The tag class used in tag clouds and search
  9.  * 
  10.  * @package alpha::model
  11.  * @since 1.0
  12.  * @author John Collins <dev@alphaframework.org>
  13.  * @version $Id: TagObject.inc 1341 2011-03-17 15:02:02Z johnc $
  14.  * @license http://www.opensource.org/licenses/bsd-license.php The BSD License
  15.  * @copyright Copyright (c) 2011, John Collins (founder of Alpha Framework).
  16.  *  All rights reserved.
  17.  * 
  18.  *  <pre>
  19.  *  Redistribution and use in source and binary forms, with or
  20.  *  without modification, are permitted provided that the
  21.  *  following conditions are met:
  22.  * 
  23.  *  * Redistributions of source code must retain the above
  24.  *    copyright notice, this list of conditions and the
  25.  *    following disclaimer.
  26.  *  * Redistributions in binary form must reproduce the above
  27.  *    copyright notice, this list of conditions and the
  28.  *    following disclaimer in the documentation and/or other
  29.  *    materials provided with the distribution.
  30.  *  * Neither the name of the Alpha Framework nor the names
  31.  *    of its contributors may be used to endorse or promote
  32.  *    products derived from this software without specific
  33.  *    prior written permission.
  34.  *   
  35.  *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  36.  *  CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  37.  *  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  38.  *  MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  39.  *  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
  40.  *  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  41.  *  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  42.  *  NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  43.  *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  44.  *  HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  45.  *  CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
  46.  *  OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  47.  *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  48.  *  </pre>
  49.  *  
  50.  */
  51. class TagObject extends AlphaDAO {
  52.     /**
  53.      * The name of the class of the object which is tagged
  54.      *
  55.      * @var String 
  56.      * @since 1.0
  57.      */
  58.     protected $taggedClass;
  59.     
  60.     /**
  61.      * The OID of the object which is tagged
  62.      *
  63.      * @var Integer 
  64.      * @since 1.0
  65.      */
  66.     protected $taggedOID;
  67.     
  68.     /**
  69.      * The content of the tag
  70.      *
  71.      * @var String 
  72.      * @since 1.0
  73.      */
  74.     protected $content;
  75.     
  76.     /**
  77.      * An array of data display labels for the class properties
  78.      * 
  79.      * @var array 
  80.      * @since 1.0
  81.      */
  82.     protected $dataLabels = array("OID"=>"Tag ID#","taggedClass"=>"Class Name","taggedOID"=>"Tagged Object ID#","content"=>"Tag");
  83.     
  84.     /**
  85.      * The name of the database table for the class
  86.      * 
  87.      * @var string 
  88.      * @since 1.0
  89.      */
  90.     const TABLE_NAME = 'Tag';
  91.     
  92.     /**
  93.      * Trace logger
  94.      * 
  95.      * @var Logger 
  96.      * @since 1.0
  97.      */
  98.     private static $logger null;
  99.     
  100.     /**
  101.      * The constructor
  102.      * 
  103.      * @since 1.0
  104.      */
  105.     public function __construct({
  106.         self::$logger new Logger('TagObject');
  107.             
  108.         // ensure to call the parent constructor
  109.         parent::__construct();
  110.         $this->taggedClass = new String();
  111.         $this->taggedOID = new Integer();
  112.         $this->content = new String();
  113.     }
  114.     
  115.     /**
  116.      * Returns an array of TagObjects matching the class and OID provided
  117.      * 
  118.      * @param $taggedClass The class name of the DAO that has been tagged.
  119.      * @param $taggedOID The Object ID of the DAO that has been tagged.
  120.      * @return array 
  121.      * @since 1.0
  122.      * @throws AlphaException
  123.      */
  124.     public function loadTags($taggedClass$taggedOID{
  125.         global $config;        
  126.         
  127.         $sqlQuery "SELECT OID FROM ".$this->getTableName()." WHERE taggedOID='$taggedOID' AND taggedClass='$taggedClass' ORDER BY OID";
  128.         
  129.         $this->lastQuery = $sqlQuery;
  130.         
  131.         if(!$result AlphaDAO::getConnection()->query($sqlQuery)) {
  132.             throw new AlphaException('Failed to object OIDs, MySql error is ['.AlphaDAO::getConnection()->error.'], query ['.$sqlQuery.']');
  133.             return array();
  134.         }
  135.         
  136.         // now build an array of objects to be returned
  137.         $objects array();
  138.         $count 0;
  139.         $BOClass get_class($this);
  140.         
  141.         while($row $result->fetch_array(MYSQLI_ASSOC)) {
  142.             $obj new $BOClass();
  143.             $obj->load($row['OID']);
  144.             $objects[$count$obj;
  145.             $count++;
  146.         }
  147.         
  148.         return $objects;
  149.     }
  150.     
  151.     /**
  152.      * Returns a hash array of the most popular tags based on their occurence in the database,
  153.      * ordered by alphabet and restricted to the a count matching the $limit supplied.  The
  154.      * returned has array uses the tag content as a key and the database value as a value.
  155.      *  
  156.      * @param $limit 
  157.      * @return array 
  158.      * @since 1.0
  159.      * @throws AlphaException
  160.      */
  161.     public static function getPopularTagsArray($limit{
  162.         global $config;        
  163.         
  164.         $sqlQuery "SELECT content, count(*) as count FROM `tag` GROUP BY content ORDER BY count DESC LIMIT $limit";
  165.         
  166.         $this->lastQuery = $sqlQuery;
  167.         
  168.         if(!$result AlphaDAO::getConnection()->query($sqlQuery)) {
  169.             throw new AlphaException('Failed to query the tags table, MySql error is ['.AlphaDAO::getConnection()->error.'], query ['.$sqlQuery.']');
  170.             return array();
  171.         }
  172.         
  173.         // now build an array of tags to be returned
  174.         $popTags array();        
  175.         
  176.         while($row $result->fetch_array(MYSQLI_ASSOC)) {            
  177.             $popTags[$row['content']] $row['count'];            
  178.         }
  179.         
  180.         // sort the array by content key before returning
  181.         ksort($popTags);        
  182.         return $popTags;
  183.     }
  184.     
  185.     /**
  186.      * Use this callback to create the tclass_toid__tcontent unique table index
  187.      * 
  188.      * @since 1.0
  189.      * @throws AlphaException
  190.      */
  191.     protected function after_checkIndexes_callback({
  192.         $indexNames $this->getIndexes();
  193.         $indexExists false;
  194.         
  195.         foreach ($indexNames as $index{                    
  196.             if ('tclass_toid_tcontent_unq_idx' == $index{
  197.                 $indexExists true;
  198.             }
  199.         }
  200.         
  201.         if(!$indexExists{
  202.             $sqlQuery 'CREATE UNIQUE INDEX tclass_toid_tcontent_unq_idx ON '.$this->getTableName().' (taggedClass,taggedOID,content);';
  203.                 
  204.             $this->lastQuery = $sqlQuery;
  205.         
  206.             if(!$result AlphaDAO::getConnection()->query($sqlQuery)) {
  207.                 throw new AlphaException('Failed to create the index [tclass_toid_tcontent_unq_idx] on ['.$this->getTableName().'], error is ['.AlphaDAO::getConnection()->error.']');
  208.             }
  209.         }
  210.     }
  211.  
  212.     /**
  213.      * Splits the passed content by spaces, filters (removes) stop words from stopwords.ini,
  214.      * and returns an array of TagObject instances.
  215.      * 
  216.      * @param $content 
  217.      * @param $taggedClass Optionally provide a BO class name
  218.      * @param $taggedOID Optionally provide a BO instance OID
  219.      * @param $applyStopwords Defaults true, set to false if you want to ignore the stopwords.
  220.      * @return array 
  221.      * @throws AlphaException
  222.      * @since 1.0
  223.      */
  224.     public static function tokenize($content$taggedClass=''$taggedOID=''$applyStopwords=true{
  225.         if(self::$logger == null)
  226.             self::$logger new Logger('TagObject');
  227.             
  228.         global $config;
  229.         
  230.         // apply stop words
  231.         $lowerWords preg_split("/[\s,.:]+/"$content);
  232.         
  233.         array_walk($lowerWords'TagObject::lowercaseArrayElement');
  234.         
  235.         if($applyStopwords{
  236.             if(file_exists($config->get('sysRoot').'config/stopwords-'.$config->get('sysStopwordsSize').'.ini')) {        
  237.                 $stopwords file($config->get('sysRoot').'config/stopwords-'.$config->get('sysStopwordsSize').'.ini'FILE_IGNORE_NEW_LINES);
  238.             }elseif(file_exists($config->get('sysRoot').'alpha/stopwords-'.$config->get('sysStopwordsSize').'.ini')) {
  239.                 $stopwords file($config->get('sysRoot').'alpha/stopwords-'.$config->get('sysStopwordsSize').'.ini'FILE_IGNORE_NEW_LINES);
  240.             }else{
  241.                 throw new AlphaException('Unable to find a stopwords-'.$config->get('sysStopwordsSize').'.ini file in the application!');
  242.             }
  243.             
  244.             array_walk($stopwords'TagObject::lowercaseArrayElement');
  245.             
  246.             $filtered array_diff($lowerWords$stopwords);
  247.         }else{
  248.             $filtered $lowerWords;
  249.         }
  250.         
  251.         $tagObjects array();
  252.         $tagContents array();
  253.         foreach($filtered as $tagContent{
  254.             // we only want to create word tags
  255.             if(AlphaValidator::isAlpha($tagContent)) {
  256.                 // just making sure that we haven't added this one in already
  257.                 if(!in_array($tagContent$tagContents&& !empty($tagContent)) {
  258.                     $tag new TagObject();
  259.                     $tag->set('content'trim(strtolower($tagContent)));
  260.                     if(!empty($taggedClass))
  261.                         $tag->set('taggedClass'$taggedClass);
  262.                     if(!empty($taggedOID))
  263.                         $tag->set('taggedOID'$taggedOID);
  264.                     
  265.                     array_push($tagObjects$tag);
  266.                     array_push($tagContents$tagContent);
  267.                 }
  268.             }
  269.         }
  270.         
  271.         self::$logger->debug('Tags generated: ['.var_export($tagContentstrue).']');
  272.         return $tagObjects;
  273.     }
  274.     
  275.     /**
  276.      * Applies trim() and strtolower to the array element passed by reference
  277.      * 
  278.      * @param $element 
  279.      * @param $key (not required)
  280.      */
  281.     private static function lowercaseArrayElement(&$element$key{
  282.         $element trim(strtolower($element));
  283.     }
  284.     
  285.     /**
  286.      * Cleans tag content by remocing white spaces and converting to lowercase.
  287.      * 
  288.      * @param $content 
  289.      * @return string 
  290.      */
  291.     public static function cleanTagContent($content{
  292.         return trim(strtolower(str_replace(' '''$content)));
  293.     }
  294. }
  295.  
  296. ?>

Documentation generated on Thu, 17 Mar 2011 16:44:56 +0000 by phpDocumentor 1.4.3