The system of access to documents for MODX
good day to All.
Currently writing for modx using individual documents for each normal user.
Because to score these documents admin didn't want to (if the site everything will be okay, there will be too much and the admin panel will start to slow down), I decided to make them into a separate database table, via a single resource.
Thus, we consider our requirements to document (at least, I had these):
For a start, let us estimate the structure of the document record in the database:
After you define the structure, it became clear that to do this set of functions will be a controversial decision, therefore, was selected with the PLO.
Well, at this stage, remember that the objects are convenient to reuse in other modules(snippets, in this case), so use the save this snippet in a static file docs.php(which also gives a chance to quickly connect Ajax, if necessary), and add the test, not whether this snippet to another just for our class this way:
Now to connect the Document class in another snippet, it is sufficient to write:
the
Now that all preparations are made, work will start by the Document class.
We first define the data of our document:
the
In the constructor we will only know who we deliver and not what he needs, which will allow, for example, using the same class object, to create a variety of documents to the user directly.
the
Further suppose that we want an object of that class we were given? In other words, public methods.
Obviously, this:
the
Also throw in the fact that we want this class gave me the opportunity to do:
the
Here, these functions are:
Thus, the logical part of our code independent of the specific database, completed. We now turn to the lower level, working directly with the database in MODX using PDO.
That's the whole Document class. Pretty simple, IMHO.
Now see what does our snippet TryLoadDocument?
So...
For a better understanding it may be easier to see the code in one block:
For a correct output we use three simple chunks:
* — if for some reason the form does not appear ever worth checking out, and a component is installed If?
And a simple snippet to retrieve parameter from the address bar:
The final code snippet TryLoadDocument can be found here: pastebin.com/R55bPUCH
Well, everything is almost ready, it remains only to attach it to your content online with your template.
Code in the content field for the resource is:
the
The Textarea with the text of our document(from the chunk DocText) should be wrapped in any WYSIWYG editor, I used CKeditor.
the
* — for this I defined TV ExtraHeaders, added it in <head> in the template, and there, where needed additional headers to the resource, set the value of this TV. Can add it directly in the chunk DocText before the textarea, but do not recommend doing so(it is necessary to separate code and data).
Currently writing for modx using individual documents for each normal user.
Because to score these documents admin didn't want to (if the site everything will be okay, there will be too much and the admin panel will start to slow down), I decided to make them into a separate database table, via a single resource.
Thus, we consider our requirements to document (at least, I had these):
-
the
- the document must have a title and content; the
- the document must be type (for easier search of documents of the same type);
- From the site owner and his lawyers have random access to any of the documents; the
- the website Owner and the people who allowed it, should be able to give their users the rights to view and edit the arbitrary document; the
- any registered user can obtain the right to view only or also edit the document at an arbitrary time or permanently.
the document owner always has access to its editing and viewing; the
1. The data structure definition
For a start, let us estimate the structure of the document record in the database:
Structure of each document
//Snippet TryLoadDocument
<?php
/**
So, all the documents stored in the database like this(converted to JSON format for better readability):
{
"type":"agreement" - the type of document, text, short, examples: carta, license, etc.
"title":"Contract" - the document title
"text":"Example. The text of the Treaty. Sign here: ______ ", - the text of the document, XSS controls CLeditor, is not our concern. Contains the entire text of a document with all the markup tags.
"owner":29, is the owner of the document, that is someone our website it has concluded. he in any case have the right to look and edit the document(since it is "his")
"edit":[29,555,34,52] - those who can edit the document.
!IMPORTANT! the user groups Administrator,Jurists have access to ANY document!
"view":[5677,599677,5999898677,855677] - those who are opening the page http://.../docs?doc_id=5 see this document(but not edit you can)
"view-temp":[{"id":5,"until":1413640050},{"id":9,"until":1413640100},{"id":7,"until":1413640050}] - similar view, but "until"(timestamp format) indicates up to what point of time you need to consider this record(after this point it is deleted)
"edit-temp":[{"id":5,"until":1413640050},{"id":9,"until":1413640100},{"id":7,"until":1413640050}] - same as edit but "until"(timestamp format) indicates up to what point of time you need to consider this record(after this point it is deleted)
}
this query such a table to create:
CREATE TABLE IF NOT EXISTS `documents` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id document',
`type` varchar(255) NOT NULL COMMENT 'document type',
`title` varchar(255) NOT NULL COMMENT 'title of document',
`text` text NOT NULL COMMENT 'the text of the document',
`owner` bigint(20) NOT NULL COMMENT 'the owner of the dock',
`edit` text NOT NULL COMMENT 'all users who have rights to view and edit',
`edit-temp` text NOT NULL COMMENT 'temporary edit permissions',
`view` text NOT NULL COMMENT 'all users who have rights to view',
`view-temp` text NOT NULL COMMENT 'temporary edit permissions',
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=cp1251 COMMENT='Personal documents of users here...';
*/
2. Snippet TryLoadDocument
2.1 Providing portability
After you define the structure, it became clear that to do this set of functions will be a controversial decision, therefore, was selected with the PLO.
Well, at this stage, remember that the objects are convenient to reuse in other modules(snippets, in this case), so use the save this snippet in a static file docs.php(which also gives a chance to quickly connect Ajax, if necessary), and add the test, not whether this snippet to another just for our class this way:
Check whether you are using the snippet as the source of the Document class
<?php
if(DOC_API_MODE!="API")//if only need the Document class, this part of the code will not run)
{
...// execute code snippet
}
Now to connect the Document class in another snippet, it is sufficient to write:
the
define("DOC_API_MODE","API");
include_once 'docs.php';
2.2 Write common business logic class
Now that all preparations are made, work will start by the Document class.
We first define the data of our document:
the
private $data;//here all the data of the document in an associative array(e.g. $data['title'] - title of the document)
private $uid;//=user id — id of the person who is trying to use this document(or create)
private $modx;//for working with modx API
In the constructor we will only know who we deliver and not what he needs, which will allow, for example, using the same class object, to create a variety of documents to the user directly.
the
public function __construct($modx)
{//because access to the $modx in functions is not(at least for me), we will give her the option
$this- > modx=$modx;
$this->uid=$this- > modx->user->get('id');//the document object can only be created from the name of the current user
}
Further suppose that we want an object of that class we were given? In other words, public methods.
Obviously, this:
the
-
the
- Title and content of the document; the
- whether the current user can see the document? the
- whether the current user can edit the document? the
- does he have the right to grant rights to others?
Also throw in the fact that we want this class gave me the opportunity to do:
the
-
the
- to Load a document by its number(id) will happen next in the text, working directly with the database; the
- Save the document in its current form — will happen next in the text, working directly with the database; the
- to Create a new document, sets the title, text, and the ability to edit it.
Here, these functions are:
Public methods
The easiest access to the fields outside the class:
the
Now checking permissions + create a new document from the given data:
the
public function &__set ( $name , $value )
{//outside(not using functions) can only change title and text
$allowed=["title","text"];
if(in_array($name,$allowed))
{
if($this- > editAllowed())//if the current user can edit
$this->data[$name]=$value;
}
}
public function &__get ( $name )
{//outside the class to directly receive the field values can all of the lists edit & view, as well as the owner...
if($this- > isOwner() || $this->viewAllowed() || $this- > editAllowed())
{
switch ($name)
{
case "title":return $this->data['title'];
case "text": return $this->data['text'];
case "id": return $this->data['id'];
case "uid": return $this->uid;
}
}
return 'forbidden';
}
Now checking permissions + create a new document from the given data:
Here work directly with the database yet
Helper function to cleanse the document from obsolete temporary permits:
the
public function MakeNew($type,$title,$text)//to create a document template, or generated dynamically
{
$this->data['text']=$text;//text document
$this->data['title']=$title;//title
$this->data['view']=[];//who can view the document
$this->data['view-temp']=[];
$this->data['edit']=[];//who can edit the document
$this->data['edit-temp']=[];
$this->load($this- > saveAsNew($type));//save the Doc and upload it in the normal form
}
public function viewAllowed()
{//returns true if this user can view the document, otherwise false..
$allowed= $this- > isOwner()//if the requestor is the Creator of the document
|| in_array($this->uid,$this->data['view']);//or has the right to view it
if($allowed)
return true;
else
for($i=0; $i<count($this->data['view-temp']);$i++)
if($this->data['view-temp'][$i]->id==$this->uid)
return $this->data['view-temp'][$i]->until > time();
return false;
}
public function editAllowed()
{//returns true if this user can edit the document, otherwise false..
$allowed = $this- > isOwner ()|| // if the requestor is the Creator of the document
in_array($this->uid,$this->data['edit']);//requesting if you can edit the document
if($allowed)
return true;
else
for($i=0; $i<count($this->data['edit-temp']);$i++)
if($this->data['edit-temp'][$i]->id==$this->uid)
return $this->data['edit-temp'][$i]->until > time();
//temporary access fields through '- > ' because of the principle of the decoding function json_decode
}
public function manageAllowed()
{//true if this user can give others access to the document. false otherwise.
return $this->modx->user->isMember('Jurists')||$this->modx->user->isMember('Administrator');
}
public function allow($new_user,$can_edit,$time=0)
{
//to give someone access to a document. $new_user - to whom to give,
//$can_edit - can edit(only if the requestor itself can edit, or it won't work)
//$time - what time to give the right(default is 0 - forever. measured in seconds
$user_id=(int)$new_user;
if($user_id!=0 && $this->manageAllowed())
if($can_edit)
{
if($this- > editAllowed())
{
if($time==0)//give the rights forever
$this->data['edit'][]=$user_id;
else//give rights for $time seconds
$this->data['edit-temp'][]=["id"=>$user_id,"until"=>time()+$time];
}
}
else
{
if($time==0)//give the rights forever
$this->data['view'][]=$user_id;
else//give rights for $time seconds
$this->data['view-temp'][]=["id"=>$user_id,"until"=>time()+$time];
}
}
public function isOwner()
{
$usual=$this->uid==$this->data['owner'];//owner permissions are:
if($usual) return true;//the owner,
else//special accounts
return $this->manageAllowed();
}
Helper function to cleanse the document from obsolete temporary permits:
the
private function clearTemp()
{//clears all arrays of temporary permits who have passed the validity
if(count($this->data['view-temp'])+count($this->data['edit-temp']) > 0)//if at least some temporary data there
{
for($i=0; $i<count($this->data['view-temp']);$i++)
//delete all temporary permits that have expiration date before the current time(time())
{
if($this->data['view-temp'][$i]->until < time())
unset($this->data['view-temp'][$i]);
}
$this->data['view-temp']=array_values($this->data['view-temp']);//just fix the problems with the indices( [1,3,5]=>[0,1,2)]
for($i=0; $i<count($this->data['edit-temp']);$i++)
//delete all temporary permits that have expiration date before the current time(time())
{
if($this->data['edit-temp'][$i]->until < time())
unset($this->data['edit-temp'][$i]);
}
$this->data['edit-temp'] = array_values($this->data['edit-temp']);//just fix the problems with the indices( [1,3,5]=>[0,1,2)]
$this->save();//save changes
}
}
2.3 Write functions to work with a specific database.
Thus, the logical part of our code independent of the specific database, completed. We now turn to the lower level, working directly with the database in MODX using PDO.
Work directly with the database
public function load($id)
{//loads the document from the database(it's right enough with anyone, that's just not any will be able the data class to)
$sql="SELECT * FROM `documents` WHERE `id`=:id";
$query = new xPDOCriteria($this- > modx, $sql,array(':id'=>$id));
if($query->prepare() && $query->stmt->execute())
{//if the data is successfully loaded
$this->data = $query->stmt->fetchAll(PDO::FETCH_ASSOC)[0];
if(count($this->data)==0) return false;//if came the empty reply, report a fail of zagruzki
$this->data['edit']=json_decode($this->data['edit']);///extract the list of those eligible to edit in an array
$this->data['edit-temp']=json_decode($this->data['edit-temp']);///extract the list has a temporary right to edit the array
$this->data['view']=json_decode($this->data['view']);///extract the list of those eligible to view the array
$this->data['view-temp']=json_decode($this->data['view-temp']);///extract the list has a temporary right to view the array
$this->clearTemp();//clear arrays view-temp & edit-ended from temp permissions
return true;//once we got here, we report that everything is OK
}
else return false;//if not run the query, report the fail download
}
public function save()
{//saves the new value of the document in the database
$sql="UPDATE `documents` SET `title`=:title, `text`=text, `view`=' view, `edit`=:edit `view-temp`=:viewtemp, `edit-temp`=:edittemp WHERE `id`=:id";//query template
$this->data['view']=json_encode($this->data['view']);///pack a list having the right view into a string
$this->data['view-temp']=json_encode($this->data['view-temp']);///pack the list of those eligible for temporary viewing in a row
$this->data['edit']=json_encode($this->data['edit']);///pack a list having the right to edit the string
$this->data['edit-temp']=json_encode($this->data['edit-temp']);///pack the list of those eligible for temporary edit to the line
$query=new xPDOCriteria($this- > modx, $sql,
[":title"=>$this->data['title'],":text"=>$this->data['text'],":edit"=>$this->data['edit'],":view"=>$this->data['view'],":edittemp"=>$this->data['edit-temp'],":viewtemp"=>$this->data['view-temp'],":id"=>$this->data["id"]]);//inline data
$query->prepare() && $query->stmt->execute();//execute the query
//convert strings back into arrays
$this->data['view']=json_decode($this->data['view']);
$this->data['view-temp']=json_decode($this->data['view-temp']);
$this->data['edit']=json_decode($this->data['edit']);
$this->data['edit-temp']=json_decode($this->data['edit-temp']);
}
private function saveAsNew($type)
{//stores the already completed document as a new record of type $type
$sql="INSERT INTO `documents` (`title`,`text`,`view`,`edit`,`owner`,`type`) VALUES(:title,:text,:view,:edit,:uid,:type)";//query template
$this->data['view']=json_encode($this->data['view']);///pack a list having the right view into a string
$this->data['edit']=json_encode($this->data['edit']);///pack a list having the right to edit the string
$this->data['view-temp']=json_encode($this->data['view-temp']);///pack a list having the right view into a string
$this->data['edit-temp']=json_encode($this->data['edit-temp']);///pack a list having the right to edit the string
$query=new xPDOCriteria($this- > modx, $sql,
[":title"=>$this->data['title'],":text"=>$this->data['text'],":edit"=>$this->data['edit'],":view"=>$this->data['view'],":uid"=>$this->uid,":type"=>$type]);//inline data
//loggerman create a new document, useful for debugging and to see how the template data is populated
//$this- > modx- > log(modX::LOG_LEVEL_ERROR,"running query: ".$query- > toSQL());
$query->prepare(); $query->stmt->execute();//execute the query
return $this- > modx->lastInsertId();//return id of the created Doc
}
That's the whole Document class. Pretty simple, IMHO.
2.4 Executable code snippet
Now see what does our snippet TryLoadDocument?
So...
Running code snippet TryLoadDoc — parse
Check came to us anonymous(its id is 0), in this case, send it login.
if($modx->user->get('id')==0)//if on page came anon,
{
$modx- > sendRedirect($modx- > makeUrl(14));//send it to the page number 14, this is where we enter the system.
exit;//just in case redirect is not SUDDENLY tripped, completing the script for sure(instead of a page is just a white screen)
}
Trying to load the requested document(the resource that uses this snippet is of the form /docs?doc_id=N).
$doc=new Document($modx);//create object to work with the document for logged in user page
if(!$doc->load($_GET['doc_id']))//try to load a Doc from the dB
{//if failed, exit...
return 'Document not found...';
}
Fill in the placeholders with the values that will enable further do not show the edit form of the document and edit the permissions for that those who are unable to do this.
//!!! here is the chunk Rights whether to display the edit field access
$modx- > setPlaceholder('CanManage',$doc->manageAllowed()?'true':'false');
//!!! here is the chunk DocText whether to display the edit form
$modx->setPlaceholder('CanEdit',$doc->editAllowed()?'true':'false');
Then a simple function that parses what you entered as a user in the form field editing rights.
function DataToUID($userstr,$modx)//for pulling the numbers with the user number of the field "user"
{
$link_rgx="/(.*uid=)([\d]{1,})(.*)/";//the regular season for links of the form http://*a path to personal account*?uid=56
$id_rgx="/([^\w]{0,})([\d]{1,})/";//the regular season user id(before and after numbers could be spaces)
if(preg_match($link_rgx,$userstr))
{//for URLs of the http://*a path to personal account*?uid=56
$r="$2";
return preg_replace($link_rgx,$r,$userstr);
} else
if(preg_match($id_rgx,$userstr))//if the input was "234", for example
{
$r="$2";
return preg_replace($id_rgx,$r,$userstr);//return only the number
} else//this is not the ID of the user and not link to it LK? then maybe it's nick?
{
$usr=$modx- > getObject('modUser',["username"=>$userstr]);//trying to find a user with the same name
return $usr?$usr->get('id'):'-1';
}
}
Treated the addition of rights, if any.
if(isset($_POST['add']))//if the user pressed the button "add rights to user...
{
$userID=(int)DataToUID($_POST['userid'],$modx);//pulls the user id from the form field 'userid'
if($userID!='-1')//if the user has been
if($_POST['allow']=="edit")//if you need to add privileges to edit and view(specified form field 'allow')
{
//write in log
$modx- > log(modX::LOG_LEVEL_ERROR,"Attempt to grant rights to edit the document #".$doc->id." to user #".$doc->uid." user #".$userID);
$doc->allow($userID,true,(int)$_POST['length']);
$doc->save();
} else
if($_POST['allow']=="view")//// if you need to add rights to view(set the form field 'allow')
{
//write in log
$modx- > log(modX::LOG_LEVEL_ERROR,"Attempt to give rights to view the document #".$doc->id." to user #".$doc->uid." user #".$userID);
$doc->allow($userID,false,(int)$_POST['length']);
$doc->save();
}
}else $modx- > log(modX::LOG_LEVEL_ERROR,"DataToUID failed. (".$_POST['userid'].")");//if instead of the username passed garbage, and write it to the log
}
edit the Processed document, if it exists
if(isset($_POST['edit']))//if the user has edited the document and pressed "save"
{
$modx- > log(modX::LOG_LEVEL_ERROR,"Attempt to edit the text of the document #".$doc->id." to user #".$doc->uid);//write to the log
if(!empty($_POST["text"]))//if the new version of the document is not empty(no sense in empty docks)
{
$doc->text=$_POST["text"];//set the field text to the new value
$doc->save();
$modx- > log(modX::LOG_LEVEL_ERROR,"an Edited text of the document #".$doc->id." to user #".$doc->uid);//write to the log
}
}
Return the placeholder [[+doc]] the content of the resource, consisting of a document and forms to edit it, to which the user access.
/**********data Output in the form*************/
if(!isset($_POST['ajax']))//if we are not called via Ajax, and for a page to load.
{
$output="";
//ship dock, if not, the object he will understand
//pass the chunk header DocTitle option, the title property, that is the title of the document. to check access it is not our concern.
$output.=$modx- > getChunk('DocTitle',['title'=>$doc->title]);
//pass the chunk header DocText parameter title, i.e. the title of the document. to check access it is not our concern.
$output.=$modx- > getChunk('DocText',['text'=>$doc->text]);
$modx- > setPlaceholder('doc', $output);
return ";
}
For a better understanding it may be easier to see the code in one block:
Running code snippet TryLoadDocument entirely
if($modx->user->get('id')==0)//if on page came anon,
{
$modx- > sendRedirect($modx- > makeUrl(14));//send it to the page number 14, this is where we enter the system.
exit;//just in case redirect is not SUDDENLY tripped, completing the script for sure(instead of strancice is just a white screen)
}
/*******/
$doc=new Document($modx);//create object to work with the document for logged in user page
if(!$doc->load($_GET['doc_id']))//try to load a Doc from the dB
{//if failed, exit...
return 'Document not found...';
}
//!!! here is the chunk Rights whether to display the edit field access
$modx- > setPlaceholder('CanManage',$doc->manageAllowed()?'true':'false');
//!!! here is the chunk DocText whether to display the edit form
$modx- > setPlaceholder('CanEdit',$doc- > editAllowed()?'true':'false');
DataToUID function($userstr,$modx)//for pulling the numbers with the user number of the field "user"
{
$link_rgx="/(.*uid=)([\d]{1,})(.*)/";//the regular season for links of the form http://*a path to personal account*?uid=56
$id_rgx="/([^\w]{0,})([\d]{1,})/";//the regular season user id(before and after numbers could be spaces)
if(preg_match($link_rgx,$userstr))
{//for URLs of the http://*a path to personal account*?uid=56
$r="$2";
return preg_replace($link_rgx,$r,$userstr);
} else
if(preg_match($id_rgx,$userstr))//if the input was "234", for example
{
$r="$2";
return preg_replace($id_rgx,$r,$userstr);//return only the number
} else//this is not the ID of the user and not link to it LK? then maybe it's nick?
{
$usr=$modx- > getObject('modUser',["username"=>$userstr]);//trying to find a user with the same name
return $usr?$usr->get('id'):'-1';
}
}
/*********These two mode shapes***********/
if(isset($_POST['add']))//if the user pressed the button "add rights to user...
{
$userID=(int)DataToUID($_POST['userid'],$modx);//pulls the user id from the form field 'userid'
if($userID!='-1')//if the user has been
{
if($_POST['allow']=="edit")//if you need to add privileges to edit and view(specified form field 'allow')
{
//write in log
$doc->allow($userID,true,(int)$_POST['length']);
$doc->save();
} else
if($_POST['allow']=="view")//// if you need to add rights to view(set the form field 'allow')
{
//write in log
$modx- > log(modX::LOG_LEVEL_ERROR,"Attempt to give rights to view the document #".$doc->id." to user #".$doc->uid." user #".$userID);
$doc->allow($userID,false,(int)$_POST['length']);
$doc->save();
}
}else $modx- > log(modX::LOG_LEVEL_ERROR,"DataToUID failed. (".$_POST['userid'].")");//if instead of the username passed garbage, and write it to the log
}
if(isset($_POST['edit']))//if the user has edited the document and pressed "save"
{
$modx- > log(modX::LOG_LEVEL_ERROR,"Attempt to edit the text of the document #".$doc->id." to user #".$doc->uid);//write to the log
if(!empty($_POST["text"]))//if the new version of the document is not empty(no sense in empty docks)
{
$doc->text=$_POST["text"];//set the field text to the new value
$doc->save();
$modx- > log(modX::LOG_LEVEL_ERROR,"an Edited text of the document #".$doc->id." to user #".$doc->uid);//write to the log
}
}
/**********Data output in the form*************/
if(!isset($_POST['ajax']))//if we are not called via Ajax, and for a page to load.
{
$output="";
//ship dock, if not, the object he will understand
//pass the chunk header DocTitle option, the title property, that is the title of the document. to check access it is not our concern.
$output.=$modx- > getChunk('DocTitle',['title'=>$doc->title]);
//pass the chunk header DocText parameter title, i.e. the title of the document. to check access it is not our concern.
$output.=$modx- > getChunk('DocText',['text'=>$doc->text]);
$modx- > setPlaceholder('doc', $output);
return ";
}
return 'Error...';//for normal here where we do not have to be, so return something to explain the problem
3. Formatting the received data and output to the page
3.1 is Required chunks
For a correct output we use three simple chunks:
Rights form with edit rights
<form action="[[~[[*id]]]]?doc_id=[[!GET? ¶m=`doc_id`]]" method="post" >
<fieldset><span>to Give users the right...</span><input type="text" name="userid" style="
background: white;
width: 340px;
padding: 5px;
font-size: 14px;
margin: 0 15px;
"/>
on
<select name="allow">
<option value="view" selected="selected">view</option>
<option value="edit">view and edit</option>
</select>
<select name="length">
<option value="60">1 min.</option>
<option value="600">10 minutes.</option>
<option value="3600">hour.</option>
<option value="86400">day.</option>
<option value="0">forever.</option>
</select>
<input type="hidden" name="add" value="1" />
</fieldset>
<input type="submit" value="Give rights!"/>
</form>
DocTitle template display title of the document.
<h2>[[!+title]]</h2>
DoctText* — template text of the document
[[!If? &subject=`[[!+CanEdit]]` &operator=`EQ` &operand=`true` &then=`<form action="[[~[[*id]]]]?doc_id=[[!GET? ¶m=`doc_id`]]" method="post">
<input type="submit" value="Save new text of the agreement..."/>`]]
<textarea id="text" name="text" >
[[+text]]
</textarea>
<script type="text/javascript"> CKEDITOR.replace( 'text' ); CKEDITOR.config.height=800; </script> <!--this line is for CKeditor-->
[[!If? &subject=`[[!+CanEdit]]` &operator=`EQ` &operand=`true` &then=`<input type="hidden" name="edit" value="1"/>
<input type="submit" value="Save new text of the agreement..."/>
</form>`]]
* — if for some reason the form does not appear ever worth checking out, and a component is installed If?
And a simple snippet to retrieve parameter from the address bar:
GET
<?
return isset($param)?$_GET[$param.""]:'0';
The final code snippet TryLoadDocument can be found here: pastebin.com/R55bPUCH
Well, everything is almost ready, it remains only to attach it to your content online with your template.
3.2 Resource to work with the document
Code in the content field for the resource is:
the
[[!TryLoadDocument]]
[[!If? &subject=`[[!+CanManage]]` &operator=`EQ` &operand=`true` &then=`[[$Rights]]`]]
[[!+doc]]
[[!If? &subject=`[[!+CanManage]]` &operator=`EQ` &operand=`true` &then=`[[$Rights]]`]]
The Textarea with the text of our document(from the chunk DocText) should be wrapped in any WYSIWYG editor, I used CKeditor.
the
<script src="//cdn.ckeditor.com/4.4.5/full/ckeditor.js"></script>
* — for this I defined TV ExtraHeaders, added it in <head> in the template, and there, where needed additional headers to the resource, set the value of this TV. Can add it directly in the chunk DocText before the textarea, but do not recommend doing so(it is necessary to separate code and data).
4. An example of using the Document class in another snippet
Let's say you want the snippet to others to create their own documents current user:
the
<?php
...
define("DOC_API_MODE","API");
include_once 'docs.php';
...
$doc= new Document($modx);
$title="Contract";
$text=$modx- > getChunk('agreement_template');//suppose we have a chunk with the document template
//in the same call, he could pass some parameters
$doc->MakeNew('agreement',$title,$text);//ready, we created the document
...
In this article I tried to show how the idea goes to logic later in the code and in the end — in the working mechanism.
Hopefully, someone will find it useful.
I apologize in advance for errors in the text of the article (though I tried to catch). Experience writing large texts I have. I will appreciate any comments.
Комментарии
Отправить комментарий